blob: c687ab52fafac7d01abc5f551d72475169856a0e [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)
89 self.binary = 1
90
91
92 def __del__(self):
93 self.close()
94
95
96 def __getattr__(self, name):
Barry Warsaw99142272003-02-08 03:18:58 +000097 """Many methods we can just pass through to the DB object.
98 (See below)
99 """
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000100 return getattr(self.db, name)
101
102
103 #-----------------------------------
104 # Dictionary access methods
105
106 def __len__(self):
107 return len(self.db)
108
109
110 def __getitem__(self, key):
111 data = self.db[key]
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000112 return pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000113
114
115 def __setitem__(self, key, value):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000116 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000117 self.db[key] = data
118
119
120 def __delitem__(self, key):
121 del self.db[key]
122
123
124 def keys(self, txn=None):
125 if txn != None:
126 return self.db.keys(txn)
127 else:
128 return self.db.keys()
129
130
131 def items(self, txn=None):
132 if txn != None:
133 items = self.db.items(txn)
134 else:
135 items = self.db.items()
136 newitems = []
137
138 for k, v in items:
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000139 newitems.append( (k, pickle.loads(v)) )
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000140 return newitems
141
142 def values(self, txn=None):
143 if txn != None:
144 values = self.db.values(txn)
145 else:
146 values = self.db.values()
147
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000148 return map(pickle.loads, values)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000149
150 #-----------------------------------
151 # Other methods
152
Gregory P. Smith1281f762004-03-16 18:50:26 +0000153 def __append(self, value, txn=None):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000154 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000155 return self.db.append(data, txn)
156
Gregory P. Smith1281f762004-03-16 18:50:26 +0000157 def append(self, value, txn=None):
Gregory P. Smith5c5f1702007-10-12 19:13:19 +0000158 if self.get_type() == db.DB_RECNO:
Gregory P. Smith1281f762004-03-16 18:50:26 +0000159 self.append = self.__append
160 return self.append(value, txn=txn)
Gregory P. Smith5c5f1702007-10-12 19:13:19 +0000161 raise DBShelveError("append() only supported when dbshelve opened with filetype=dbshelve.db.DB_RECNO")
Gregory P. Smith1281f762004-03-16 18:50:26 +0000162
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000163
164 def associate(self, secondaryDB, callback, flags=0):
165 def _shelf_callback(priKey, priData, realCallback=callback):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000166 data = pickle.loads(priData)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000167 return realCallback(priKey, data)
168 return self.db.associate(secondaryDB, _shelf_callback, flags)
169
170
Martin v. Löwiscccc58d2007-08-10 08:36:56 +0000171 def get(self, key, default=_unspecified, txn=None, flags=0):
172 # If no default is given, we must not pass one to the
173 # extension module, so that an exception can be raised if
174 # set_get_returns_none is turned off.
175 if default is _unspecified:
176 data = self.db.get(key, txn=txn, flags=flags)
177 # if this returns, the default value would be None
178 default = None
179 else:
180 data = self.db.get(key, default, txn=txn, flags=flags)
181 if data is default:
182 return data
183 return pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000184
185 def get_both(self, key, value, txn=None, flags=0):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000186 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000187 data = self.db.get(key, data, txn, flags)
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000188 return pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000189
190
191 def cursor(self, txn=None, flags=0):
192 c = DBShelfCursor(self.db.cursor(txn, flags))
193 c.binary = self.binary
194 return c
195
196
197 def put(self, key, value, txn=None, flags=0):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000198 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000199 return self.db.put(key, data, txn, flags)
200
201
202 def join(self, cursorList, flags=0):
203 raise NotImplementedError
204
205
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000206 def __contains__(self, key):
Guido van Rossum20435132006-08-21 00:21:47 +0000207 return self.db.has_key(key)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000208
209
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000210 #----------------------------------------------
211 # Methods allowed to pass-through to self.db
212 #
213 # close, delete, fd, get_byteswapped, get_type, has_key,
214 # key_range, open, remove, rename, stat, sync,
215 # upgrade, verify, and all set_* methods.
216
217
218#---------------------------------------------------------------------------
219
220class DBShelfCursor:
221 """
222 """
223 def __init__(self, cursor):
224 self.dbc = cursor
225
226 def __del__(self):
227 self.close()
228
229
230 def __getattr__(self, name):
231 """Some methods we can just pass through to the cursor object. (See below)"""
232 return getattr(self.dbc, name)
233
234
235 #----------------------------------------------
236
237 def dup(self, flags=0):
238 return DBShelfCursor(self.dbc.dup(flags))
239
240
241 def put(self, key, value, flags=0):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000242 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000243 return self.dbc.put(key, data, flags)
244
245
246 def get(self, *args):
247 count = len(args) # a method overloading hack
248 method = getattr(self, 'get_%d' % count)
Neal Norwitzd9108552006-03-17 08:00:19 +0000249 method(*args)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000250
251 def get_1(self, flags):
252 rec = self.dbc.get(flags)
253 return self._extract(rec)
254
255 def get_2(self, key, flags):
256 rec = self.dbc.get(key, flags)
257 return self._extract(rec)
258
259 def get_3(self, key, value, flags):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000260 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000261 rec = self.dbc.get(key, flags)
262 return self._extract(rec)
263
264
265 def current(self, flags=0): return self.get_1(flags|db.DB_CURRENT)
266 def first(self, flags=0): return self.get_1(flags|db.DB_FIRST)
267 def last(self, flags=0): return self.get_1(flags|db.DB_LAST)
268 def next(self, flags=0): return self.get_1(flags|db.DB_NEXT)
269 def prev(self, flags=0): return self.get_1(flags|db.DB_PREV)
270 def consume(self, flags=0): return self.get_1(flags|db.DB_CONSUME)
271 def next_dup(self, flags=0): return self.get_1(flags|db.DB_NEXT_DUP)
272 def next_nodup(self, flags=0): return self.get_1(flags|db.DB_NEXT_NODUP)
273 def prev_nodup(self, flags=0): return self.get_1(flags|db.DB_PREV_NODUP)
274
275
276 def get_both(self, key, value, flags=0):
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_both(key, flags)
279 return self._extract(rec)
280
281
282 def set(self, key, flags=0):
283 rec = self.dbc.set(key, flags)
284 return self._extract(rec)
285
286 def set_range(self, key, flags=0):
287 rec = self.dbc.set_range(key, flags)
288 return self._extract(rec)
289
290 def set_recno(self, recno, flags=0):
291 rec = self.dbc.set_recno(recno, flags)
292 return self._extract(rec)
293
294 set_both = get_both
295
296 def _extract(self, rec):
297 if rec is None:
298 return None
299 else:
300 key, data = rec
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000301 return key, pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000302
303 #----------------------------------------------
304 # Methods allowed to pass-through to self.dbc
305 #
306 # close, count, delete, get_recno, join_item
307
308
309#---------------------------------------------------------------------------