99febb29bdcefe877885d2edff7d082ab5ee4e05
1 #$Id: back_anydbm.py,v 1.3 2001-07-25 01:23:07 richard Exp $
3 import anydbm, os, marshal
4 from roundup import hyperdb, date
6 #
7 # Now the database
8 #
9 class Database(hyperdb.Database):
10 """A database for storing records containing flexible data types."""
12 def __init__(self, storagelocator, journaltag=None):
13 """Open a hyperdatabase given a specifier to some storage.
15 The meaning of 'storagelocator' depends on the particular
16 implementation of the hyperdatabase. It could be a file name,
17 a directory path, a socket descriptor for a connection to a
18 database over the network, etc.
20 The 'journaltag' is a token that will be attached to the journal
21 entries for any edits done on the database. If 'journaltag' is
22 None, the database is opened in read-only mode: the Class.create(),
23 Class.set(), and Class.retire() methods are disabled.
24 """
25 self.dir, self.journaltag = storagelocator, journaltag
26 self.classes = {}
28 #
29 # Classes
30 #
31 def __getattr__(self, classname):
32 """A convenient way of calling self.getclass(classname)."""
33 return self.classes[classname]
35 def addclass(self, cl):
36 cn = cl.classname
37 if self.classes.has_key(cn):
38 raise ValueError, cn
39 self.classes[cn] = cl
41 def getclasses(self):
42 """Return a list of the names of all existing classes."""
43 l = self.classes.keys()
44 l.sort()
45 return l
47 def getclass(self, classname):
48 """Get the Class object representing a particular class.
50 If 'classname' is not a valid class name, a KeyError is raised.
51 """
52 return self.classes[classname]
54 #
55 # Class DBs
56 #
57 def clear(self):
58 for cn in self.classes.keys():
59 db = os.path.join(self.dir, 'nodes.%s'%cn)
60 anydbm.open(db, 'n')
61 db = os.path.join(self.dir, 'journals.%s'%cn)
62 anydbm.open(db, 'n')
64 def getclassdb(self, classname, mode='r'):
65 ''' grab a connection to the class db that will be used for
66 multiple actions
67 '''
68 path = os.path.join(os.getcwd(), self.dir, 'nodes.%s'%classname)
69 if os.path.exists(path):
70 return anydbm.open(path, mode)
71 else:
72 return anydbm.open(path, 'n')
74 #
75 # Nodes
76 #
77 def addnode(self, classname, nodeid, node):
78 ''' add the specified node to its class's db
79 '''
80 db = self.getclassdb(classname, 'c')
82 # convert the instance data to builtin types
83 properties = self.classes[classname].properties
84 for key in properties.keys():
85 if properties[key].isDateType:
86 node[key] = node[key].get_tuple()
87 elif properties[key].isIntervalType:
88 node[key] = node[key].get_tuple()
90 # now save the marshalled data
91 db[nodeid] = marshal.dumps(node)
92 db.close()
93 setnode = addnode
95 def getnode(self, classname, nodeid, cldb=None):
96 ''' add the specified node to its class's db
97 '''
98 db = cldb or self.getclassdb(classname)
99 if not db.has_key(nodeid):
100 raise IndexError, nodeid
101 res = marshal.loads(db[nodeid])
103 # convert the marshalled data to instances
104 properties = self.classes[classname].properties
105 for key in res.keys():
106 if key == self.RETIRED_FLAG: continue
107 if properties[key].isDateType:
108 res[key] = date.Date(res[key])
109 elif properties[key].isIntervalType:
110 res[key] = date.Interval(res[key])
112 if not cldb: db.close()
113 return res
115 def hasnode(self, classname, nodeid, cldb=None):
116 ''' add the specified node to its class's db
117 '''
118 db = cldb or self.getclassdb(classname)
119 res = db.has_key(nodeid)
120 if not cldb: db.close()
121 return res
123 def countnodes(self, classname, cldb=None):
124 db = cldb or self.getclassdb(classname)
125 return len(db.keys())
126 if not cldb: db.close()
127 return res
129 def getnodeids(self, classname, cldb=None):
130 db = cldb or self.getclassdb(classname)
131 res = db.keys()
132 if not cldb: db.close()
133 return res
135 #
136 # Journal
137 #
138 def addjournal(self, classname, nodeid, action, params):
139 ''' Journal the Action
140 'action' may be:
142 'create' or 'set' -- 'params' is a dictionary of property values
143 'link' or 'unlink' -- 'params' is (classname, nodeid, propname)
144 'retire' -- 'params' is None
145 '''
146 entry = (nodeid, date.Date().get_tuple(), self.journaltag, action,
147 params)
148 db = anydbm.open(os.path.join(self.dir, 'journals.%s'%classname), 'c')
149 if db.has_key(nodeid):
150 s = db[nodeid]
151 l = marshal.loads(db[nodeid])
152 l.append(entry)
153 else:
154 l = [entry]
155 db[nodeid] = marshal.dumps(l)
156 db.close()
158 def getjournal(self, classname, nodeid):
159 ''' get the journal for id
160 '''
161 # attempt to open the journal - in some rare cases, the journal may
162 # not exist
163 try:
164 db = anydbm.open(os.path.join(self.dir, 'journals.%s'%classname),
165 'r')
166 except anydbm.open, error:
167 if error.args[0] != 2: raise
168 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 anydbm 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 '''
202 #
203 #$Log: not supported by cvs2svn $
204 #Revision 1.2 2001/07/23 08:20:44 richard
205 #Moved over to using marshal in the bsddb and anydbm backends.
206 #roundup-admin now has a "freshen" command that'll load/save all nodes (not
207 # retired - mod hyperdb.Class.list() so it lists retired nodes)
208 #
209 #