Code

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