Code

stupid typo
[roundup.git] / roundup / backends / back_anydbm.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_anydbm.py,v 1.6 2001-08-07 00:24:42 richard Exp $
20 import anydbm, 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             anydbm.open(db, 'n')
78             db = os.path.join(self.dir, 'journals.%s'%cn)
79             anydbm.open(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 anydbm.open(path, mode)
88         else:
89             return anydbm.open(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')
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 key == self.RETIRED_FLAG: continue
124             if properties[key].isDateType:
125                 res[key] = date.Date(res[key])
126             elif properties[key].isIntervalType:
127                 res[key] = date.Interval(res[key])
129         if not cldb: db.close()
130         return res
132     def hasnode(self, classname, nodeid, cldb=None):
133         ''' add the specified node to its class's db
134         '''
135         db = cldb or self.getclassdb(classname)
136         res = db.has_key(nodeid)
137         if not cldb: db.close()
138         return res
140     def countnodes(self, classname, cldb=None):
141         db = cldb or self.getclassdb(classname)
142         return len(db.keys())
143         if not cldb: db.close()
144         return res
146     def getnodeids(self, classname, cldb=None):
147         db = cldb or self.getclassdb(classname)
148         res = db.keys()
149         if not cldb: db.close()
150         return res
152     #
153     # Journal
154     #
155     def addjournal(self, classname, nodeid, action, params):
156         ''' Journal the Action
157         'action' may be:
159             'create' or 'set' -- 'params' is a dictionary of property values
160             'link' or 'unlink' -- 'params' is (classname, nodeid, propname)
161             'retire' -- 'params' is None
162         '''
163         entry = (nodeid, date.Date().get_tuple(), self.journaltag, action,
164             params)
165         db = anydbm.open(os.path.join(self.dir, 'journals.%s'%classname), 'c')
166         if db.has_key(nodeid):
167             s = db[nodeid]
168             l = marshal.loads(db[nodeid])
169             l.append(entry)
170         else:
171             l = [entry]
172         db[nodeid] = marshal.dumps(l)
173         db.close()
175     def getjournal(self, classname, nodeid):
176         ''' get the journal for id
177         '''
178         # attempt to open the journal - in some rare cases, the journal may
179         # not exist
180         try:
181             db = anydbm.open(os.path.join(self.dir, 'journals.%s'%classname),
182                 'r')
183         except anydbm.open, error:
184             if error.args[0] != 2: raise
185             return []
186         journal = marshal.loads(db[nodeid])
187         res = []
188         for entry in journal:
189             (nodeid, date_stamp, self.journaltag, action, params) = entry
190             date_obj = date.Date(date_stamp)
191             res.append((nodeid, date_obj, self.journaltag, action, params))
192         db.close()
193         return res
195     def close(self):
196         ''' Close the Database - we must release the circular refs so that
197             we can be del'ed and the underlying anydbm connections closed
198             cleanly.
199         '''
200         self.classes = None
203     #
204     # Basic transaction support
205     #
206     # TODO: well, write these methods (and then use them in other code)
207     def register_action(self):
208         ''' Register an action to the transaction undo log
209         '''
211     def commit(self):
212         ''' Commit the current transaction, start a new one
213         '''
215     def rollback(self):
216         ''' Reverse all actions from the current transaction
217         '''
220 #$Log: not supported by cvs2svn $
221 #Revision 1.5  2001/08/07 00:15:51  richard
222 #Added the copyright/license notice to (nearly) all files at request of
223 #Bizar Software.
225 #Revision 1.4  2001/07/30 01:41:36  richard
226 #Makes schema changes mucho easier.
228 #Revision 1.3  2001/07/25 01:23:07  richard
229 #Added the Roundup spec to the new documentation directory.
231 #Revision 1.2  2001/07/23 08:20:44  richard
232 #Moved over to using marshal in the bsddb and anydbm backends.
233 #roundup-admin now has a "freshen" command that'll load/save all nodes (not
234 # retired - mod hyperdb.Class.list() so it lists retired nodes)