Code

Moved the data stringification up into the hyperdb.Class class' get, set
[roundup.git] / roundup / backends / back_bsddb3.py
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_bsddb3.py,v 1.9 2001-10-09 23:58:10 richard Exp $
20 import bsddb3, 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             bsddb3.btopen(db, 'c')
78             db = os.path.join(self.dir, 'journals.%s'%cn)
79             bsddb3.btopen(db, 'c')
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 bsddb3.btopen(path, mode)
88         else:
89             return bsddb3.btopen(path, 'c')
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         # now save the marshalled data
99         db[nodeid] = marshal.dumps(node)
100         db.close()
101     setnode = addnode
103     def getnode(self, classname, nodeid, cldb=None):
104         ''' add the specified node to its class's db
105         '''
106         db = cldb or self.getclassdb(classname)
107         if not db.has_key(nodeid):
108             raise IndexError, nodeid
109         res = marshal.loads(db[nodeid])
110         if not cldb: db.close()
111         return res
113     def hasnode(self, classname, nodeid, cldb=None):
114         ''' add the specified node to its class's db
115         '''
116         db = cldb or self.getclassdb(classname)
117         res = db.has_key(nodeid)
118         if not cldb: db.close()
119         return res
121     def countnodes(self, classname, cldb=None):
122         db = cldb or self.getclassdb(classname)
123         return len(db.keys())
124         if not cldb: db.close()
125         return res
127     def getnodeids(self, classname, cldb=None):
128         db = cldb or self.getclassdb(classname)
129         res = db.keys()
130         if not cldb: db.close()
131         return res
133     #
134     # Journal
135     #
136     def addjournal(self, classname, nodeid, action, params):
137         ''' Journal the Action
138         'action' may be:
140             'create' or 'set' -- 'params' is a dictionary of property values
141             'link' or 'unlink' -- 'params' is (classname, nodeid, propname)
142             'retire' -- 'params' is None
143         '''
144         entry = (nodeid, date.Date().get_tuple(), self.journaltag, action,
145             params)
146         db = bsddb3.btopen(os.path.join(self.dir, 'journals.%s'%classname), 'c')
147         if db.has_key(nodeid):
148             s = db[nodeid]
149             l = marshal.loads(db[nodeid])
150             l.append(entry)
151         else:
152             l = [entry]
153         db[nodeid] = marshal.dumps(l)
154         db.close()
156     def getjournal(self, classname, nodeid):
157         ''' get the journal for id
158         '''
159         # attempt to open the journal - in some rare cases, the journal may
160         # not exist
161         try:
162             db = bsddb3.btopen(os.path.join(self.dir, 'journals.%s'%classname),
163                 'r')
164         except bsddb3.error, error:
165             if error.args[0] != 2: raise
166             return []
167         # mor handling of bad journals
168         if not db.has_key(nodeid): return []
169         journal = marshal.loads(db[nodeid])
170         res = []
171         for entry in journal:
172             (nodeid, date_stamp, self.journaltag, action, params) = entry
173             date_obj = date.Date(date_stamp)
174             res.append((nodeid, date_obj, self.journaltag, action, params))
175         db.close()
176         return res
178     def close(self):
179         ''' Close the Database - we must release the circular refs so that
180             we can be del'ed and the underlying bsddb connections closed
181             cleanly.
182         '''
183         self.classes = None
186     #
187     # Basic transaction support
188     #
189     # TODO: well, write these methods (and then use them in other code)
190     def register_action(self):
191         ''' Register an action to the transaction undo log
192         '''
194     def commit(self):
195         ''' Commit the current transaction, start a new one
196         '''
198     def rollback(self):
199         ''' Reverse all actions from the current transaction
200         '''
203 #$Log: not supported by cvs2svn $
204 #Revision 1.8  2001/10/09 07:25:59  richard
205 #Added the Password property type. See "pydoc roundup.password" for
206 #implementation details. Have updated some of the documentation too.
208 #Revision 1.7  2001/08/12 06:32:36  richard
209 #using isinstance(blah, Foo) now instead of isFooType
211 #Revision 1.6  2001/08/07 00:24:42  richard
212 #stupid typo
214 #Revision 1.5  2001/08/07 00:15:51  richard
215 #Added the copyright/license notice to (nearly) all files at request of
216 #Bizar Software.
218 #Revision 1.4  2001/08/03 02:45:47  anthonybaxter
219 #'n' -> 'c' for create.
221 #Revision 1.3  2001/07/30 02:36:23  richard
222 #Handle non-existence of db files in the other backends (code from anydbm).
224 #Revision 1.2  2001/07/30 01:41:36  richard
225 #Makes schema changes mucho easier.
227 #Revision 1.1  2001/07/24 04:26:03  anthonybaxter
228 #bsddb3 implementation. For now, it's the bsddb implementation with a "3"
229 #added in crayon.
231 #Revision 1.4  2001/07/23 08:25:33  richard
232 #more handling of bad journals
234 #Revision 1.3  2001/07/23 08:20:44  richard
235 #Moved over to using marshal in the bsddb and anydbm backends.
236 #roundup-admin now has a "freshen" command that'll load/save all nodes (not
237 # retired - mod hyperdb.Class.list() so it lists retired nodes)
239 #Revision 1.2  2001/07/23 07:56:05  richard
240 #Storing only marshallable data in the db - no nasty pickled class references.
242 #Revision 1.1  2001/07/23 07:22:13  richard
243 #*sigh* some databases have _foo.so as their underlying implementation.
244 #This time for sure, Rocky.
246 #Revision 1.1  2001/07/23 07:15:57  richard
247 #Moved the backends into the backends package. Anydbm hasn't been tested at all.
249 #Revision 1.1  2001/07/23 06:23:41  richard
250 #moved hyper_bsddb.py to the new backends package as bsddb.py
252 #Revision 1.2  2001/07/22 12:09:32  richard
253 #Final commit of Grande Splite
255 #Revision 1.1  2001/07/22 11:58:35  richard
256 #More Grande Splite