Code

9f3124081171957316d70e5a67caf0f5064bac45
[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.8 2001-09-29 13:27:00 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 = {}
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()
108         # now save the marshalled data
109         db[nodeid] = marshal.dumps(node)
110         db.close()
111     setnode = addnode
113     def getnode(self, classname, nodeid, cldb=None):
114         ''' add the specified node to its class's db
115         '''
116         db = cldb or self.getclassdb(classname)
117         if not db.has_key(nodeid):
118             raise IndexError, nodeid
119         res = marshal.loads(db[nodeid])
121         # convert the marshalled data to instances
122         properties = self.classes[classname].properties
123         for key in properties.keys():
124             if key == self.RETIRED_FLAG: continue
125             if isinstance(properties[key], hyperdb.Date):
126                 res[key] = date.Date(res[key])
127             elif isinstance(properties[key], hyperdb.Interval):
128                 res[key] = date.Interval(res[key])
130         if not cldb: db.close()
131         return res
133     def hasnode(self, classname, nodeid, cldb=None):
134         ''' add the specified node to its class's db
135         '''
136         db = cldb or self.getclassdb(classname)
137         res = db.has_key(nodeid)
138         if not cldb: db.close()
139         return res
141     def countnodes(self, classname, cldb=None):
142         db = cldb or self.getclassdb(classname)
143         return len(db.keys())
144         if not cldb: db.close()
145         return res
147     def getnodeids(self, classname, cldb=None):
148         db = cldb or self.getclassdb(classname)
149         res = db.keys()
150         if not cldb: db.close()
151         return res
153     #
154     # Journal
155     #
156     def addjournal(self, classname, nodeid, action, params):
157         ''' Journal the Action
158         'action' may be:
160             'create' or 'set' -- 'params' is a dictionary of property values
161             'link' or 'unlink' -- 'params' is (classname, nodeid, propname)
162             'retire' -- 'params' is None
163         '''
164         entry = (nodeid, date.Date().get_tuple(), self.journaltag, action,
165             params)
166         db = anydbm.open(os.path.join(self.dir, 'journals.%s'%classname), 'c')
167         if db.has_key(nodeid):
168             s = db[nodeid]
169             l = marshal.loads(db[nodeid])
170             l.append(entry)
171         else:
172             l = [entry]
173         db[nodeid] = marshal.dumps(l)
174         db.close()
176     def getjournal(self, classname, nodeid):
177         ''' get the journal for id
178         '''
179         # attempt to open the journal - in some rare cases, the journal may
180         # not exist
181         try:
182             db = anydbm.open(os.path.join(self.dir, 'journals.%s'%classname),
183                 'r')
184         except anydbm.open, error:
185             if error.args[0] != 2: raise
186             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 anydbm connections closed
199             cleanly.
200         '''
201         self.classes = None
204     #
205     # Basic transaction support
206     #
207     def commit(self):
208         ''' Commit the current transactions.
209         '''
210         # lock the DB
211         for action, classname, entry in self.transactions:
212             # write the node, figure what's changed for the journal.
213             pass
214         # unlock the DB
216     def rollback(self):
217         ''' Reverse all actions from the current transaction.
218         '''
219         self.transactions = []
222 #$Log: not supported by cvs2svn $
223 #Revision 1.7  2001/08/12 06:32:36  richard
224 #using isinstance(blah, Foo) now instead of isFooType
226 #Revision 1.6  2001/08/07 00:24:42  richard
227 #stupid typo
229 #Revision 1.5  2001/08/07 00:15:51  richard
230 #Added the copyright/license notice to (nearly) all files at request of
231 #Bizar Software.
233 #Revision 1.4  2001/07/30 01:41:36  richard
234 #Makes schema changes mucho easier.
236 #Revision 1.3  2001/07/25 01:23:07  richard
237 #Added the Roundup spec to the new documentation directory.
239 #Revision 1.2  2001/07/23 08:20:44  richard
240 #Moved over to using marshal in the bsddb and anydbm backends.
241 #roundup-admin now has a "freshen" command that'll load/save all nodes (not
242 # retired - mod hyperdb.Class.list() so it lists retired nodes)