baa80703bff0dc997658300d9c24b7fc87a242b5
1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17 #
18 #$Id: back_bsddb.py,v 1.12 2001-11-21 02:34:18 richard Exp $
20 import bsddb, os, marshal
21 from roundup import hyperdb, date, password
23 #
24 # Now the database
25 #
26 class Database(hyperdb.Database):
27 """A database for storing records containing flexible data types."""
29 def __init__(self, storagelocator, journaltag=None):
30 """Open a hyperdatabase given a specifier to some storage.
32 The meaning of 'storagelocator' depends on the particular
33 implementation of the hyperdatabase. It could be a file name,
34 a directory path, a socket descriptor for a connection to a
35 database over the network, etc.
37 The 'journaltag' is a token that will be attached to the journal
38 entries for any edits done on the database. If 'journaltag' is
39 None, the database is opened in read-only mode: the Class.create(),
40 Class.set(), and Class.retire() methods are disabled.
41 """
42 self.dir, self.journaltag = storagelocator, journaltag
43 self.classes = {}
45 #
46 # Classes
47 #
48 def __getattr__(self, classname):
49 """A convenient way of calling self.getclass(classname)."""
50 return self.classes[classname]
52 def addclass(self, cl):
53 cn = cl.classname
54 if self.classes.has_key(cn):
55 raise ValueError, cn
56 self.classes[cn] = cl
58 def getclasses(self):
59 """Return a list of the names of all existing classes."""
60 l = self.classes.keys()
61 l.sort()
62 return l
64 def getclass(self, classname):
65 """Get the Class object representing a particular class.
67 If 'classname' is not a valid class name, a KeyError is raised.
68 """
69 return self.classes[classname]
71 #
72 # Class DBs
73 #
74 def clear(self):
75 for cn in self.classes.keys():
76 db = os.path.join(self.dir, 'nodes.%s'%cn)
77 bsddb.btopen(db, 'n')
78 db = os.path.join(self.dir, 'journals.%s'%cn)
79 bsddb.btopen(db, 'n')
81 def getclassdb(self, classname, mode='r'):
82 ''' grab a connection to the class db that will be used for
83 multiple actions
84 '''
85 path = os.path.join(os.getcwd(), self.dir, 'nodes.%s'%classname)
86 if os.path.exists(path):
87 return bsddb.btopen(path, mode)
88 else:
89 return bsddb.btopen(path, 'n')
91 #
92 # Nodes
93 #
94 def addnode(self, classname, nodeid, node):
95 ''' add the specified node to its class's db
96 '''
97 db = self.getclassdb(classname, 'c')
98 db[nodeid] = marshal.dumps(node)
99 db.close()
100 setnode = addnode
102 def getnode(self, classname, nodeid, cldb=None):
103 ''' add the specified node to its class's db
104 '''
105 db = cldb or self.getclassdb(classname)
106 if not db.has_key(nodeid):
107 raise IndexError, nodeid
108 res = marshal.loads(db[nodeid])
109 if not cldb: db.close()
110 return res
112 def hasnode(self, classname, nodeid, cldb=None):
113 ''' add the specified node to its class's db
114 '''
115 db = cldb or self.getclassdb(classname)
116 res = db.has_key(nodeid)
117 if not cldb: db.close()
118 return res
120 def countnodes(self, classname, cldb=None):
121 db = cldb or self.getclassdb(classname)
122 return len(db.keys())
123 if not cldb: db.close()
124 return res
126 def getnodeids(self, classname, cldb=None):
127 db = cldb or self.getclassdb(classname)
128 res = db.keys()
129 if not cldb: db.close()
130 return res
132 #
133 # Journal
134 #
135 def addjournal(self, classname, nodeid, action, params):
136 ''' Journal the Action
137 'action' may be:
139 'create' or 'set' -- 'params' is a dictionary of property values
140 'link' or 'unlink' -- 'params' is (classname, nodeid, propname)
141 'retire' -- 'params' is None
142 '''
143 entry = (nodeid, date.Date().get_tuple(), self.journaltag, action,
144 params)
145 db = bsddb.btopen(os.path.join(self.dir, 'journals.%s'%classname), 'c')
146 if db.has_key(nodeid):
147 s = db[nodeid]
148 l = marshal.loads(db[nodeid])
149 l.append(entry)
150 else:
151 l = [entry]
152 db[nodeid] = marshal.dumps(l)
153 db.close()
155 def getjournal(self, classname, nodeid):
156 ''' get the journal for id
157 '''
158 # attempt to open the journal - in some rare cases, the journal may
159 # not exist
160 try:
161 db = bsddb.btopen(os.path.join(self.dir, 'journals.%s'%classname),
162 'r')
163 except bsddb.error, error:
164 if error.args[0] != 2: raise
165 return []
166 # mor handling of bad journals
167 if not db.has_key(nodeid): return []
168 journal = marshal.loads(db[nodeid])
169 res = []
170 for entry in journal:
171 (nodeid, date_stamp, self.journaltag, action, params) = entry
172 date_obj = date.Date(date_stamp)
173 res.append((nodeid, date_obj, self.journaltag, action, params))
174 db.close()
175 return res
177 def close(self):
178 ''' Close the Database - we must release the circular refs so that
179 we can be del'ed and the underlying bsddb connections closed
180 cleanly.
181 '''
182 self.classes = {}
185 #
186 # Basic transaction support
187 #
188 # TODO: well, write these methods (and then use them in other code)
189 def register_action(self):
190 ''' Register an action to the transaction undo log
191 '''
193 def commit(self):
194 ''' Commit the current transaction, start a new one
195 '''
197 def rollback(self):
198 ''' Reverse all actions from the current transaction
199 '''
201 #
202 #$Log: not supported by cvs2svn $
203 #Revision 1.11 2001/10/09 23:58:10 richard
204 #Moved the data stringification up into the hyperdb.Class class' get, set
205 #and create methods. This means that the data is also stringified for the
206 #journal call, and removes duplication of code from the backends. The
207 #backend code now only sees strings.
208 #
209 #Revision 1.10 2001/10/09 07:25:59 richard
210 #Added the Password property type. See "pydoc roundup.password" for
211 #implementation details. Have updated some of the documentation too.
212 #
213 #Revision 1.9 2001/08/12 06:32:36 richard
214 #using isinstance(blah, Foo) now instead of isFooType
215 #
216 #Revision 1.8 2001/08/07 00:24:42 richard
217 #stupid typo
218 #
219 #Revision 1.7 2001/08/07 00:15:51 richard
220 #Added the copyright/license notice to (nearly) all files at request of
221 #Bizar Software.
222 #
223 #Revision 1.6 2001/07/30 02:36:23 richard
224 #Handle non-existence of db files in the other backends (code from anydbm).
225 #
226 #Revision 1.5 2001/07/30 01:41:36 richard
227 #Makes schema changes mucho easier.
228 #
229 #Revision 1.4 2001/07/23 08:25:33 richard
230 #more handling of bad journals
231 #
232 #Revision 1.3 2001/07/23 08:20:44 richard
233 #Moved over to using marshal in the bsddb and anydbm backends.
234 #roundup-admin now has a "freshen" command that'll load/save all nodes (not
235 # retired - mod hyperdb.Class.list() so it lists retired nodes)
236 #
237 #Revision 1.2 2001/07/23 07:56:05 richard
238 #Storing only marshallable data in the db - no nasty pickled class references.
239 #
240 #Revision 1.1 2001/07/23 07:22:13 richard
241 #*sigh* some databases have _foo.so as their underlying implementation.
242 #This time for sure, Rocky.
243 #
244 #Revision 1.1 2001/07/23 07:15:57 richard
245 #Moved the backends into the backends package. Anydbm hasn't been tested at all.
246 #
247 #Revision 1.1 2001/07/23 06:23:41 richard
248 #moved hyper_bsddb.py to the new backends package as bsddb.py
249 #
250 #Revision 1.2 2001/07/22 12:09:32 richard
251 #Final commit of Grande Splite
252 #
253 #Revision 1.1 2001/07/22 11:58:35 richard
254 #More Grande Splite
255 #