Code

a7345cd681aadf6ac0e882d65d83d8e8d0731171
[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.9 2001-10-09 07:25:59 richard Exp $
20 import anydbm, 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 = {}
44         self.transactions = []
46     #
47     # Classes
48     #
49     def __getattr__(self, classname):
50         """A convenient way of calling self.getclass(classname)."""
51         return self.classes[classname]
53     def addclass(self, cl):
54         cn = cl.classname
55         if self.classes.has_key(cn):
56             raise ValueError, cn
57         self.classes[cn] = cl
59     def getclasses(self):
60         """Return a list of the names of all existing classes."""
61         l = self.classes.keys()
62         l.sort()
63         return l
65     def getclass(self, classname):
66         """Get the Class object representing a particular class.
68         If 'classname' is not a valid class name, a KeyError is raised.
69         """
70         return self.classes[classname]
72     #
73     # Class DBs
74     #
75     def clear(self):
76         for cn in self.classes.keys():
77             db = os.path.join(self.dir, 'nodes.%s'%cn)
78             anydbm.open(db, 'n')
79             db = os.path.join(self.dir, 'journals.%s'%cn)
80             anydbm.open(db, 'n')
82     def getclassdb(self, classname, mode='r'):
83         ''' grab a connection to the class db that will be used for
84             multiple actions
85         '''
86         path = os.path.join(os.getcwd(), self.dir, 'nodes.%s'%classname)
87         if os.path.exists(path):
88             return anydbm.open(path, mode)
89         else:
90             return anydbm.open(path, 'n')
92     #
93     # Nodes
94     #
95     def addnode(self, classname, nodeid, node):
96         ''' add the specified node to its class's db
97         '''
98         db = self.getclassdb(classname, 'c')
100         # convert the instance data to builtin types
101         properties = self.classes[classname].properties
102         for key in properties.keys():
103             if isinstance(properties[key], hyperdb.Date):
104                 node[key] = node[key].get_tuple()
105             elif isinstance(properties[key], hyperdb.Interval):
106                 node[key] = node[key].get_tuple()
107             elif isinstance(properties[key], hyperdb.Password):
108                 node[key] = str(node[key])
110         # now save the marshalled data
111         db[nodeid] = marshal.dumps(node)
112         db.close()
113     setnode = addnode
115     def getnode(self, classname, nodeid, cldb=None):
116         ''' add the specified node to its class's db
117         '''
118         db = cldb or self.getclassdb(classname)
119         if not db.has_key(nodeid):
120             raise IndexError, nodeid
121         res = marshal.loads(db[nodeid])
123         # convert the marshalled data to instances
124         properties = self.classes[classname].properties
125         for key in properties.keys():
126             if key == self.RETIRED_FLAG: continue
127             if isinstance(properties[key], hyperdb.Date):
128                 res[key] = date.Date(res[key])
129             elif isinstance(properties[key], hyperdb.Interval):
130                 res[key] = date.Interval(res[key])
131             elif isinstance(properties[key], hyperdb.Password):
132                 p = password.Password()
133                 p.unpack(res[key])
134                 res[key] = p
136         if not cldb: db.close()
137         return res
139     def hasnode(self, classname, nodeid, cldb=None):
140         ''' add the specified node to its class's db
141         '''
142         db = cldb or self.getclassdb(classname)
143         res = db.has_key(nodeid)
144         if not cldb: db.close()
145         return res
147     def countnodes(self, classname, cldb=None):
148         db = cldb or self.getclassdb(classname)
149         return len(db.keys())
150         if not cldb: db.close()
151         return res
153     def getnodeids(self, classname, cldb=None):
154         db = cldb or self.getclassdb(classname)
155         res = db.keys()
156         if not cldb: db.close()
157         return res
159     #
160     # Journal
161     #
162     def addjournal(self, classname, nodeid, action, params):
163         ''' Journal the Action
164         'action' may be:
166             'create' or 'set' -- 'params' is a dictionary of property values
167             'link' or 'unlink' -- 'params' is (classname, nodeid, propname)
168             'retire' -- 'params' is None
169         '''
170         entry = (nodeid, date.Date().get_tuple(), self.journaltag, action,
171             params)
172         db = anydbm.open(os.path.join(self.dir, 'journals.%s'%classname), 'c')
173         if db.has_key(nodeid):
174             s = db[nodeid]
175             l = marshal.loads(db[nodeid])
176             l.append(entry)
177         else:
178             l = [entry]
179         db[nodeid] = marshal.dumps(l)
180         db.close()
182     def getjournal(self, classname, nodeid):
183         ''' get the journal for id
184         '''
185         # attempt to open the journal - in some rare cases, the journal may
186         # not exist
187         try:
188             db = anydbm.open(os.path.join(self.dir, 'journals.%s'%classname),
189                 'r')
190         except anydbm.open, error:
191             if error.args[0] != 2: raise
192             return []
193         journal = marshal.loads(db[nodeid])
194         res = []
195         for entry in journal:
196             (nodeid, date_stamp, self.journaltag, action, params) = entry
197             date_obj = date.Date(date_stamp)
198             res.append((nodeid, date_obj, self.journaltag, action, params))
199         db.close()
200         return res
202     def close(self):
203         ''' Close the Database - we must release the circular refs so that
204             we can be del'ed and the underlying anydbm connections closed
205             cleanly.
206         '''
207         self.classes = None
210     #
211     # Basic transaction support
212     #
213     def commit(self):
214         ''' Commit the current transactions.
215         '''
216         # lock the DB
217         for action, classname, entry in self.transactions:
218             # write the node, figure what's changed for the journal.
219             pass
220         # unlock the DB
222     def rollback(self):
223         ''' Reverse all actions from the current transaction.
224         '''
225         self.transactions = []
228 #$Log: not supported by cvs2svn $
229 #Revision 1.8  2001/09/29 13:27:00  richard
230 #CGI interfaces now spit up a top-level index of all the instances they can
231 #serve.
233 #Revision 1.7  2001/08/12 06:32:36  richard
234 #using isinstance(blah, Foo) now instead of isFooType
236 #Revision 1.6  2001/08/07 00:24:42  richard
237 #stupid typo
239 #Revision 1.5  2001/08/07 00:15:51  richard
240 #Added the copyright/license notice to (nearly) all files at request of
241 #Bizar Software.
243 #Revision 1.4  2001/07/30 01:41:36  richard
244 #Makes schema changes mucho easier.
246 #Revision 1.3  2001/07/25 01:23:07  richard
247 #Added the Roundup spec to the new documentation directory.
249 #Revision 1.2  2001/07/23 08:20:44  richard
250 #Moved over to using marshal in the bsddb and anydbm backends.
251 #roundup-admin now has a "freshen" command that'll load/save all nodes (not
252 # retired - mod hyperdb.Class.list() so it lists retired nodes)