404cd7cfd5c0776b63dbfaf624a1d6c25a8c8eb6
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: hyperdb.py,v 1.61 2002-04-03 06:11:51 richard Exp $
20 __doc__ = """
21 Hyperdatabase implementation, especially field types.
22 """
24 # standard python modules
25 import re, string, weakref, os
27 # roundup modules
28 import date, password
30 DEBUG = os.environ.get('HYPERDBDEBUG', '')
32 #
33 # Types
34 #
35 class String:
36 """An object designating a String property."""
37 def __repr__(self):
38 ' more useful for dumps '
39 return '<%s>'%self.__class__
41 class Password:
42 """An object designating a Password property."""
43 def __repr__(self):
44 ' more useful for dumps '
45 return '<%s>'%self.__class__
47 class Date:
48 """An object designating a Date property."""
49 def __repr__(self):
50 ' more useful for dumps '
51 return '<%s>'%self.__class__
53 class Interval:
54 """An object designating an Interval property."""
55 def __repr__(self):
56 ' more useful for dumps '
57 return '<%s>'%self.__class__
59 class Link:
60 """An object designating a Link property that links to a
61 node in a specified class."""
62 def __init__(self, classname, do_journal='no'):
63 ''' Default is to not journal link and unlink events
64 '''
65 self.classname = classname
66 self.do_journal = do_journal == 'yes'
67 def __repr__(self):
68 ' more useful for dumps '
69 return '<%s to "%s">'%(self.__class__, self.classname)
71 class Multilink:
72 """An object designating a Multilink property that links
73 to nodes in a specified class.
75 "classname" indicates the class to link to
77 "do_journal" indicates whether the linked-to nodes should have
78 'link' and 'unlink' events placed in their journal
79 """
80 def __init__(self, classname, do_journal='no'):
81 ''' Default is to not journal link and unlink events
82 '''
83 self.classname = classname
84 self.do_journal = do_journal == 'yes'
85 def __repr__(self):
86 ' more useful for dumps '
87 return '<%s to "%s">'%(self.__class__, self.classname)
89 class DatabaseError(ValueError):
90 '''Error to be raised when there is some problem in the database code
91 '''
92 pass
95 #
96 # the base Database class
97 #
98 class Database:
99 '''A database for storing records containing flexible data types.
101 This class defines a hyperdatabase storage layer, which the Classes use to
102 store their data.
105 Transactions
106 ------------
107 The Database should support transactions through the commit() and
108 rollback() methods. All other Database methods should be transaction-aware,
109 using data from the current transaction before looking up the database.
111 An implementation must provide an override for the get() method so that the
112 in-database value is returned in preference to the in-transaction value.
113 This is necessary to determine if any values have changed during a
114 transaction.
116 '''
118 # flag to set on retired entries
119 RETIRED_FLAG = '__hyperdb_retired'
121 # XXX deviates from spec: storagelocator is obtained from the config
122 def __init__(self, config, journaltag=None):
123 """Open a hyperdatabase given a specifier to some storage.
125 The 'storagelocator' is obtained from config.DATABASE.
126 The meaning of 'storagelocator' depends on the particular
127 implementation of the hyperdatabase. It could be a file name,
128 a directory path, a socket descriptor for a connection to a
129 database over the network, etc.
131 The 'journaltag' is a token that will be attached to the journal
132 entries for any edits done on the database. If 'journaltag' is
133 None, the database is opened in read-only mode: the Class.create(),
134 Class.set(), and Class.retire() methods are disabled.
135 """
136 raise NotImplementedError
138 def __getattr__(self, classname):
139 """A convenient way of calling self.getclass(classname)."""
140 raise NotImplementedError
142 def addclass(self, cl):
143 '''Add a Class to the hyperdatabase.
144 '''
145 raise NotImplementedError
147 def getclasses(self):
148 """Return a list of the names of all existing classes."""
149 raise NotImplementedError
151 def getclass(self, classname):
152 """Get the Class object representing a particular class.
154 If 'classname' is not a valid class name, a KeyError is raised.
155 """
156 raise NotImplementedError
158 def clear(self):
159 '''Delete all database contents.
160 '''
161 raise NotImplementedError
163 def getclassdb(self, classname, mode='r'):
164 '''Obtain a connection to the class db that will be used for
165 multiple actions.
166 '''
167 raise NotImplementedError
169 def addnode(self, classname, nodeid, node):
170 '''Add the specified node to its class's db.
171 '''
172 raise NotImplementedError
174 def serialise(self, classname, node):
175 '''Copy the node contents, converting non-marshallable data into
176 marshallable data.
177 '''
178 if DEBUG: print 'serialise', classname, node
179 properties = self.getclass(classname).getprops()
180 d = {}
181 for k, v in node.items():
182 prop = properties[k]
184 if isinstance(prop, Password):
185 d[k] = str(v)
186 elif isinstance(prop, Date) and v is not None:
187 d[k] = v.get_tuple()
188 elif isinstance(prop, Interval) and v is not None:
189 d[k] = v.get_tuple()
190 else:
191 d[k] = v
192 return d
194 def setnode(self, classname, nodeid, node):
195 '''Change the specified node.
196 '''
197 raise NotImplementedError
199 def unserialise(self, classname, node):
200 '''Decode the marshalled node data
201 '''
202 if DEBUG: print 'unserialise', classname, node
203 properties = self.getclass(classname).getprops()
204 d = {}
205 for k, v in node.items():
206 # avoid properties that don't exist any more
207 if not properties.has_key(k):
208 continue
209 prop = properties[k]
210 if isinstance(prop, Date) and v is not None:
211 d[k] = date.Date(v)
212 elif isinstance(prop, Interval) and v is not None:
213 d[k] = date.Interval(v)
214 elif isinstance(prop, Password):
215 p = password.Password()
216 p.unpack(v)
217 d[k] = p
218 else:
219 d[k] = v
220 return d
222 def getnode(self, classname, nodeid, db=None, cache=1):
223 '''Get a node from the database.
224 '''
225 raise NotImplementedError
227 def hasnode(self, classname, nodeid, db=None):
228 '''Determine if the database has a given node.
229 '''
230 raise NotImplementedError
232 def countnodes(self, classname, db=None):
233 '''Count the number of nodes that exist for a particular Class.
234 '''
235 raise NotImplementedError
237 def getnodeids(self, classname, db=None):
238 '''Retrieve all the ids of the nodes for a particular Class.
239 '''
240 raise NotImplementedError
242 def storefile(self, classname, nodeid, property, content):
243 '''Store the content of the file in the database.
245 The property may be None, in which case the filename does not
246 indicate which property is being saved.
247 '''
248 raise NotImplementedError
250 def getfile(self, classname, nodeid, property):
251 '''Store the content of the file in the database.
252 '''
253 raise NotImplementedError
255 def addjournal(self, classname, nodeid, action, params):
256 ''' Journal the Action
257 'action' may be:
259 'create' or 'set' -- 'params' is a dictionary of property values
260 'link' or 'unlink' -- 'params' is (classname, nodeid, propname)
261 'retire' -- 'params' is None
262 '''
263 raise NotImplementedError
265 def getjournal(self, classname, nodeid):
266 ''' get the journal for id
267 '''
268 raise NotImplementedError
270 def pack(self, pack_before):
271 ''' pack the database
272 '''
273 raise NotImplementedError
275 def commit(self):
276 ''' Commit the current transactions.
278 Save all data changed since the database was opened or since the
279 last commit() or rollback().
280 '''
281 raise NotImplementedError
283 def rollback(self):
284 ''' Reverse all actions from the current transaction.
286 Undo all the changes made since the database was opened or the last
287 commit() or rollback() was performed.
288 '''
289 raise NotImplementedError
291 _marker = []
292 #
293 # The base Class class
294 #
295 class Class:
296 """The handle to a particular class of nodes in a hyperdatabase."""
298 def __init__(self, db, classname, **properties):
299 """Create a new class with a given name and property specification.
301 'classname' must not collide with the name of an existing class,
302 or a ValueError is raised. The keyword arguments in 'properties'
303 must map names to property objects, or a TypeError is raised.
304 """
305 self.classname = classname
306 self.properties = properties
307 self.db = weakref.proxy(db) # use a weak ref to avoid circularity
308 self.key = ''
310 # do the db-related init stuff
311 db.addclass(self)
313 def __repr__(self):
314 '''Slightly more useful representation
315 '''
316 return '<hypderdb.Class "%s">'%self.classname
318 # Editing nodes:
320 def create(self, **propvalues):
321 """Create a new node of this class and return its id.
323 The keyword arguments in 'propvalues' map property names to values.
325 The values of arguments must be acceptable for the types of their
326 corresponding properties or a TypeError is raised.
328 If this class has a key property, it must be present and its value
329 must not collide with other key strings or a ValueError is raised.
331 Any other properties on this class that are missing from the
332 'propvalues' dictionary are set to None.
334 If an id in a link or multilink property does not refer to a valid
335 node, an IndexError is raised.
336 """
337 if propvalues.has_key('id'):
338 raise KeyError, '"id" is reserved'
340 if self.db.journaltag is None:
341 raise DatabaseError, 'Database open read-only'
343 # new node's id
344 newid = str(self.count() + 1)
346 # validate propvalues
347 num_re = re.compile('^\d+$')
348 for key, value in propvalues.items():
349 if key == self.key:
350 try:
351 self.lookup(value)
352 except KeyError:
353 pass
354 else:
355 raise ValueError, 'node with key "%s" exists'%value
357 # try to handle this property
358 try:
359 prop = self.properties[key]
360 except KeyError:
361 raise KeyError, '"%s" has no property "%s"'%(self.classname,
362 key)
364 if isinstance(prop, Link):
365 if type(value) != type(''):
366 raise ValueError, 'link value must be String'
367 link_class = self.properties[key].classname
368 # if it isn't a number, it's a key
369 if not num_re.match(value):
370 try:
371 value = self.db.classes[link_class].lookup(value)
372 except (TypeError, KeyError):
373 raise IndexError, 'new property "%s": %s not a %s'%(
374 key, value, link_class)
375 elif not self.db.hasnode(link_class, value):
376 raise IndexError, '%s has no node %s'%(link_class, value)
378 # save off the value
379 propvalues[key] = value
381 # register the link with the newly linked node
382 if self.properties[key].do_journal:
383 self.db.addjournal(link_class, value, 'link',
384 (self.classname, newid, key))
386 elif isinstance(prop, Multilink):
387 if type(value) != type([]):
388 raise TypeError, 'new property "%s" not a list of ids'%key
389 link_class = self.properties[key].classname
390 l = []
391 for entry in value:
392 if type(entry) != type(''):
393 raise ValueError, 'link value must be String'
394 # if it isn't a number, it's a key
395 if not num_re.match(entry):
396 try:
397 entry = self.db.classes[link_class].lookup(entry)
398 except (TypeError, KeyError):
399 raise IndexError, 'new property "%s": %s not a %s'%(
400 key, entry, self.properties[key].classname)
401 l.append(entry)
402 value = l
403 propvalues[key] = value
405 # handle additions
406 for id in value:
407 if not self.db.hasnode(link_class, id):
408 raise IndexError, '%s has no node %s'%(link_class, id)
409 # register the link with the newly linked node
410 if self.properties[key].do_journal:
411 self.db.addjournal(link_class, id, 'link',
412 (self.classname, newid, key))
414 elif isinstance(prop, String):
415 if type(value) != type(''):
416 raise TypeError, 'new property "%s" not a string'%key
418 elif isinstance(prop, Password):
419 if not isinstance(value, password.Password):
420 raise TypeError, 'new property "%s" not a Password'%key
422 elif isinstance(prop, Date):
423 if value is not None and not isinstance(value, date.Date):
424 raise TypeError, 'new property "%s" not a Date'%key
426 elif isinstance(prop, Interval):
427 if value is not None and not isinstance(value, date.Interval):
428 raise TypeError, 'new property "%s" not an Interval'%key
430 # make sure there's data where there needs to be
431 for key, prop in self.properties.items():
432 if propvalues.has_key(key):
433 continue
434 if key == self.key:
435 raise ValueError, 'key property "%s" is required'%key
436 if isinstance(prop, Multilink):
437 propvalues[key] = []
438 else:
439 # TODO: None isn't right here, I think...
440 propvalues[key] = None
442 # done
443 self.db.addnode(self.classname, newid, propvalues)
444 self.db.addjournal(self.classname, newid, 'create', propvalues)
445 return newid
447 def get(self, nodeid, propname, default=_marker, cache=1):
448 """Get the value of a property on an existing node of this class.
450 'nodeid' must be the id of an existing node of this class or an
451 IndexError is raised. 'propname' must be the name of a property
452 of this class or a KeyError is raised.
454 'cache' indicates whether the transaction cache should be queried
455 for the node. If the node has been modified and you need to
456 determine what its values prior to modification are, you need to
457 set cache=0.
458 """
459 if propname == 'id':
460 return nodeid
462 # get the property (raises KeyErorr if invalid)
463 prop = self.properties[propname]
465 # get the node's dict
466 d = self.db.getnode(self.classname, nodeid, cache=cache)
468 if not d.has_key(propname):
469 if default is _marker:
470 if isinstance(prop, Multilink):
471 return []
472 else:
473 # TODO: None isn't right here, I think...
474 return None
475 else:
476 return default
478 return d[propname]
480 # XXX not in spec
481 def getnode(self, nodeid, cache=1):
482 ''' Return a convenience wrapper for the node.
484 'nodeid' must be the id of an existing node of this class or an
485 IndexError is raised.
487 'cache' indicates whether the transaction cache should be queried
488 for the node. If the node has been modified and you need to
489 determine what its values prior to modification are, you need to
490 set cache=0.
491 '''
492 return Node(self, nodeid, cache=cache)
494 def set(self, nodeid, **propvalues):
495 """Modify a property on an existing node of this class.
497 'nodeid' must be the id of an existing node of this class or an
498 IndexError is raised.
500 Each key in 'propvalues' must be the name of a property of this
501 class or a KeyError is raised.
503 All values in 'propvalues' must be acceptable types for their
504 corresponding properties or a TypeError is raised.
506 If the value of the key property is set, it must not collide with
507 other key strings or a ValueError is raised.
509 If the value of a Link or Multilink property contains an invalid
510 node id, a ValueError is raised.
511 """
512 if not propvalues:
513 return
515 if propvalues.has_key('id'):
516 raise KeyError, '"id" is reserved'
518 if self.db.journaltag is None:
519 raise DatabaseError, 'Database open read-only'
521 node = self.db.getnode(self.classname, nodeid)
522 if node.has_key(self.db.RETIRED_FLAG):
523 raise IndexError
524 num_re = re.compile('^\d+$')
525 for key, value in propvalues.items():
526 # check to make sure we're not duplicating an existing key
527 if key == self.key and node[key] != value:
528 try:
529 self.lookup(value)
530 except KeyError:
531 pass
532 else:
533 raise ValueError, 'node with key "%s" exists'%value
535 # this will raise the KeyError if the property isn't valid
536 # ... we don't use getprops() here because we only care about
537 # the writeable properties.
538 prop = self.properties[key]
540 # if the value's the same as the existing value, no sense in
541 # doing anything
542 if node.has_key(key) and value == node[key]:
543 del propvalues[key]
544 continue
546 # do stuff based on the prop type
547 if isinstance(prop, Link):
548 link_class = self.properties[key].classname
549 # if it isn't a number, it's a key
550 if type(value) != type(''):
551 raise ValueError, 'link value must be String'
552 if not num_re.match(value):
553 try:
554 value = self.db.classes[link_class].lookup(value)
555 except (TypeError, KeyError):
556 raise IndexError, 'new property "%s": %s not a %s'%(
557 key, value, self.properties[key].classname)
559 if not self.db.hasnode(link_class, value):
560 raise IndexError, '%s has no node %s'%(link_class, value)
562 if self.properties[key].do_journal:
563 # register the unlink with the old linked node
564 if node[key] is not None:
565 self.db.addjournal(link_class, node[key], 'unlink',
566 (self.classname, nodeid, key))
568 # register the link with the newly linked node
569 if value is not None:
570 self.db.addjournal(link_class, value, 'link',
571 (self.classname, nodeid, key))
573 elif isinstance(prop, Multilink):
574 if type(value) != type([]):
575 raise TypeError, 'new property "%s" not a list of ids'%key
576 link_class = self.properties[key].classname
577 l = []
578 for entry in value:
579 # if it isn't a number, it's a key
580 if type(entry) != type(''):
581 raise ValueError, 'link value must be String'
582 if not num_re.match(entry):
583 try:
584 entry = self.db.classes[link_class].lookup(entry)
585 except (TypeError, KeyError):
586 raise IndexError, 'new property "%s": %s not a %s'%(
587 key, entry, self.properties[key].classname)
588 l.append(entry)
589 value = l
590 propvalues[key] = value
592 # handle removals
593 if node.has_key(key):
594 l = node[key]
595 else:
596 l = []
597 for id in l[:]:
598 if id in value:
599 continue
600 # register the unlink with the old linked node
601 if self.properties[key].do_journal:
602 self.db.addjournal(link_class, id, 'unlink',
603 (self.classname, nodeid, key))
604 l.remove(id)
606 # handle additions
607 for id in value:
608 if not self.db.hasnode(link_class, id):
609 raise IndexError, '%s has no node %s'%(
610 link_class, id)
611 if id in l:
612 continue
613 # register the link with the newly linked node
614 if self.properties[key].do_journal:
615 self.db.addjournal(link_class, id, 'link',
616 (self.classname, nodeid, key))
617 l.append(id)
619 elif isinstance(prop, String):
620 if value is not None and type(value) != type(''):
621 raise TypeError, 'new property "%s" not a string'%key
623 elif isinstance(prop, Password):
624 if not isinstance(value, password.Password):
625 raise TypeError, 'new property "%s" not a Password'% key
626 propvalues[key] = value
628 elif value is not None and isinstance(prop, Date):
629 if not isinstance(value, date.Date):
630 raise TypeError, 'new property "%s" not a Date'% key
631 propvalues[key] = value
633 elif value is not None and isinstance(prop, Interval):
634 if not isinstance(value, date.Interval):
635 raise TypeError, 'new property "%s" not an Interval'% key
636 propvalues[key] = value
638 node[key] = value
640 # nothing to do?
641 if not propvalues:
642 return
644 # do the set, and journal it
645 self.db.setnode(self.classname, nodeid, node)
646 self.db.addjournal(self.classname, nodeid, 'set', propvalues)
648 def retire(self, nodeid):
649 """Retire a node.
651 The properties on the node remain available from the get() method,
652 and the node's id is never reused.
654 Retired nodes are not returned by the find(), list(), or lookup()
655 methods, and other nodes may reuse the values of their key properties.
656 """
657 if self.db.journaltag is None:
658 raise DatabaseError, 'Database open read-only'
659 node = self.db.getnode(self.classname, nodeid)
660 node[self.db.RETIRED_FLAG] = 1
661 self.db.setnode(self.classname, nodeid, node)
662 self.db.addjournal(self.classname, nodeid, 'retired', None)
664 def history(self, nodeid):
665 """Retrieve the journal of edits on a particular node.
667 'nodeid' must be the id of an existing node of this class or an
668 IndexError is raised.
670 The returned list contains tuples of the form
672 (date, tag, action, params)
674 'date' is a Timestamp object specifying the time of the change and
675 'tag' is the journaltag specified when the database was opened.
676 """
677 return self.db.getjournal(self.classname, nodeid)
679 # Locating nodes:
680 def hasnode(self, nodeid):
681 '''Determine if the given nodeid actually exists
682 '''
683 return self.db.hasnode(self.classname, nodeid)
685 def setkey(self, propname):
686 """Select a String property of this class to be the key property.
688 'propname' must be the name of a String property of this class or
689 None, or a TypeError is raised. The values of the key property on
690 all existing nodes must be unique or a ValueError is raised.
691 """
692 # TODO: validate that the property is a String!
693 self.key = propname
695 def getkey(self):
696 """Return the name of the key property for this class or None."""
697 return self.key
699 def labelprop(self, default_to_id=0):
700 ''' Return the property name for a label for the given node.
702 This method attempts to generate a consistent label for the node.
703 It tries the following in order:
704 1. key property
705 2. "name" property
706 3. "title" property
707 4. first property from the sorted property name list
708 '''
709 k = self.getkey()
710 if k:
711 return k
712 props = self.getprops()
713 if props.has_key('name'):
714 return 'name'
715 elif props.has_key('title'):
716 return 'title'
717 if default_to_id:
718 return 'id'
719 props = props.keys()
720 props.sort()
721 return props[0]
723 # TODO: set up a separate index db file for this? profile?
724 def lookup(self, keyvalue):
725 """Locate a particular node by its key property and return its id.
727 If this class has no key property, a TypeError is raised. If the
728 'keyvalue' matches one of the values for the key property among
729 the nodes in this class, the matching node's id is returned;
730 otherwise a KeyError is raised.
731 """
732 cldb = self.db.getclassdb(self.classname)
733 for nodeid in self.db.getnodeids(self.classname, cldb):
734 node = self.db.getnode(self.classname, nodeid, cldb)
735 if node.has_key(self.db.RETIRED_FLAG):
736 continue
737 if node[self.key] == keyvalue:
738 return nodeid
739 raise KeyError, keyvalue
741 # XXX: change from spec - allows multiple props to match
742 def find(self, **propspec):
743 """Get the ids of nodes in this class which link to a given node.
745 'propspec' consists of keyword args propname=nodeid
746 'propname' must be the name of a property in this class, or a
747 KeyError is raised. That property must be a Link or Multilink
748 property, or a TypeError is raised.
750 'nodeid' must be the id of an existing node in the class linked
751 to by the given property, or an IndexError is raised.
752 """
753 propspec = propspec.items()
754 for propname, nodeid in propspec:
755 # check the prop is OK
756 prop = self.properties[propname]
757 if not isinstance(prop, Link) and not isinstance(prop, Multilink):
758 raise TypeError, "'%s' not a Link/Multilink property"%propname
759 if not self.db.hasnode(prop.classname, nodeid):
760 raise ValueError, '%s has no node %s'%(prop.classname, nodeid)
762 # ok, now do the find
763 cldb = self.db.getclassdb(self.classname)
764 l = []
765 for id in self.db.getnodeids(self.classname, cldb):
766 node = self.db.getnode(self.classname, id, cldb)
767 if node.has_key(self.db.RETIRED_FLAG):
768 continue
769 for propname, nodeid in propspec:
770 property = node[propname]
771 if isinstance(prop, Link) and nodeid == property:
772 l.append(id)
773 elif isinstance(prop, Multilink) and nodeid in property:
774 l.append(id)
775 return l
777 def stringFind(self, **requirements):
778 """Locate a particular node by matching a set of its String
779 properties in a caseless search.
781 If the property is not a String property, a TypeError is raised.
783 The return is a list of the id of all nodes that match.
784 """
785 for propname in requirements.keys():
786 prop = self.properties[propname]
787 if isinstance(not prop, String):
788 raise TypeError, "'%s' not a String property"%propname
789 requirements[propname] = requirements[propname].lower()
790 l = []
791 cldb = self.db.getclassdb(self.classname)
792 for nodeid in self.db.getnodeids(self.classname, cldb):
793 node = self.db.getnode(self.classname, nodeid, cldb)
794 if node.has_key(self.db.RETIRED_FLAG):
795 continue
796 for key, value in requirements.items():
797 if node[key] and node[key].lower() != value:
798 break
799 else:
800 l.append(nodeid)
801 return l
803 def list(self):
804 """Return a list of the ids of the active nodes in this class."""
805 l = []
806 cn = self.classname
807 cldb = self.db.getclassdb(cn)
808 for nodeid in self.db.getnodeids(cn, cldb):
809 node = self.db.getnode(cn, nodeid, cldb)
810 if node.has_key(self.db.RETIRED_FLAG):
811 continue
812 l.append(nodeid)
813 l.sort()
814 return l
816 # XXX not in spec
817 def filter(self, filterspec, sort, group, num_re = re.compile('^\d+$')):
818 ''' Return a list of the ids of the active nodes in this class that
819 match the 'filter' spec, sorted by the group spec and then the
820 sort spec
821 '''
822 cn = self.classname
824 # optimise filterspec
825 l = []
826 props = self.getprops()
827 for k, v in filterspec.items():
828 propclass = props[k]
829 if isinstance(propclass, Link):
830 if type(v) is not type([]):
831 v = [v]
832 # replace key values with node ids
833 u = []
834 link_class = self.db.classes[propclass.classname]
835 for entry in v:
836 if entry == '-1': entry = None
837 elif not num_re.match(entry):
838 try:
839 entry = link_class.lookup(entry)
840 except (TypeError,KeyError):
841 raise ValueError, 'property "%s": %s not a %s'%(
842 k, entry, self.properties[k].classname)
843 u.append(entry)
845 l.append((0, k, u))
846 elif isinstance(propclass, Multilink):
847 if type(v) is not type([]):
848 v = [v]
849 # replace key values with node ids
850 u = []
851 link_class = self.db.classes[propclass.classname]
852 for entry in v:
853 if not num_re.match(entry):
854 try:
855 entry = link_class.lookup(entry)
856 except (TypeError,KeyError):
857 raise ValueError, 'new property "%s": %s not a %s'%(
858 k, entry, self.properties[k].classname)
859 u.append(entry)
860 l.append((1, k, u))
861 elif isinstance(propclass, String):
862 # simple glob searching
863 v = re.sub(r'([\|\{\}\\\.\+\[\]\(\)])', r'\\\1', v)
864 v = v.replace('?', '.')
865 v = v.replace('*', '.*?')
866 l.append((2, k, re.compile(v, re.I)))
867 else:
868 l.append((6, k, v))
869 filterspec = l
871 # now, find all the nodes that are active and pass filtering
872 l = []
873 cldb = self.db.getclassdb(cn)
874 for nodeid in self.db.getnodeids(cn, cldb):
875 node = self.db.getnode(cn, nodeid, cldb)
876 if node.has_key(self.db.RETIRED_FLAG):
877 continue
878 # apply filter
879 for t, k, v in filterspec:
880 # this node doesn't have this property, so reject it
881 if not node.has_key(k): break
883 if t == 0 and node[k] not in v:
884 # link - if this node'd property doesn't appear in the
885 # filterspec's nodeid list, skip it
886 break
887 elif t == 1:
888 # multilink - if any of the nodeids required by the
889 # filterspec aren't in this node's property, then skip
890 # it
891 for value in v:
892 if value not in node[k]:
893 break
894 else:
895 continue
896 break
897 elif t == 2 and (node[k] is None or not v.search(node[k])):
898 # RE search
899 break
900 elif t == 6 and node[k] != v:
901 # straight value comparison for the other types
902 break
903 else:
904 l.append((nodeid, node))
905 l.sort()
907 # optimise sort
908 m = []
909 for entry in sort:
910 if entry[0] != '-':
911 m.append(('+', entry))
912 else:
913 m.append((entry[0], entry[1:]))
914 sort = m
916 # optimise group
917 m = []
918 for entry in group:
919 if entry[0] != '-':
920 m.append(('+', entry))
921 else:
922 m.append((entry[0], entry[1:]))
923 group = m
924 # now, sort the result
925 def sortfun(a, b, sort=sort, group=group, properties=self.getprops(),
926 db = self.db, cl=self):
927 a_id, an = a
928 b_id, bn = b
929 # sort by group and then sort
930 for list in group, sort:
931 for dir, prop in list:
932 # sorting is class-specific
933 propclass = properties[prop]
935 # handle the properties that might be "faked"
936 # also, handle possible missing properties
937 try:
938 if not an.has_key(prop):
939 an[prop] = cl.get(a_id, prop)
940 av = an[prop]
941 except KeyError:
942 # the node doesn't have a value for this property
943 if isinstance(propclass, Multilink): av = []
944 else: av = ''
945 try:
946 if not bn.has_key(prop):
947 bn[prop] = cl.get(b_id, prop)
948 bv = bn[prop]
949 except KeyError:
950 # the node doesn't have a value for this property
951 if isinstance(propclass, Multilink): bv = []
952 else: bv = ''
954 # String and Date values are sorted in the natural way
955 if isinstance(propclass, String):
956 # clean up the strings
957 if av and av[0] in string.uppercase:
958 av = an[prop] = av.lower()
959 if bv and bv[0] in string.uppercase:
960 bv = bn[prop] = bv.lower()
961 if (isinstance(propclass, String) or
962 isinstance(propclass, Date)):
963 # it might be a string that's really an integer
964 try:
965 av = int(av)
966 bv = int(bv)
967 except:
968 pass
969 if dir == '+':
970 r = cmp(av, bv)
971 if r != 0: return r
972 elif dir == '-':
973 r = cmp(bv, av)
974 if r != 0: return r
976 # Link properties are sorted according to the value of
977 # the "order" property on the linked nodes if it is
978 # present; or otherwise on the key string of the linked
979 # nodes; or finally on the node ids.
980 elif isinstance(propclass, Link):
981 link = db.classes[propclass.classname]
982 if av is None and bv is not None: return -1
983 if av is not None and bv is None: return 1
984 if av is None and bv is None: continue
985 if link.getprops().has_key('order'):
986 if dir == '+':
987 r = cmp(link.get(av, 'order'),
988 link.get(bv, 'order'))
989 if r != 0: return r
990 elif dir == '-':
991 r = cmp(link.get(bv, 'order'),
992 link.get(av, 'order'))
993 if r != 0: return r
994 elif link.getkey():
995 key = link.getkey()
996 if dir == '+':
997 r = cmp(link.get(av, key), link.get(bv, key))
998 if r != 0: return r
999 elif dir == '-':
1000 r = cmp(link.get(bv, key), link.get(av, key))
1001 if r != 0: return r
1002 else:
1003 if dir == '+':
1004 r = cmp(av, bv)
1005 if r != 0: return r
1006 elif dir == '-':
1007 r = cmp(bv, av)
1008 if r != 0: return r
1010 # Multilink properties are sorted according to how many
1011 # links are present.
1012 elif isinstance(propclass, Multilink):
1013 if dir == '+':
1014 r = cmp(len(av), len(bv))
1015 if r != 0: return r
1016 elif dir == '-':
1017 r = cmp(len(bv), len(av))
1018 if r != 0: return r
1019 # end for dir, prop in list:
1020 # end for list in sort, group:
1021 # if all else fails, compare the ids
1022 return cmp(a[0], b[0])
1024 l.sort(sortfun)
1025 return [i[0] for i in l]
1027 def count(self):
1028 """Get the number of nodes in this class.
1030 If the returned integer is 'numnodes', the ids of all the nodes
1031 in this class run from 1 to numnodes, and numnodes+1 will be the
1032 id of the next node to be created in this class.
1033 """
1034 return self.db.countnodes(self.classname)
1036 # Manipulating properties:
1038 def getprops(self, protected=1):
1039 """Return a dictionary mapping property names to property objects.
1040 If the "protected" flag is true, we include protected properties -
1041 those which may not be modified."""
1042 d = self.properties.copy()
1043 if protected:
1044 d['id'] = String()
1045 return d
1047 def addprop(self, **properties):
1048 """Add properties to this class.
1050 The keyword arguments in 'properties' must map names to property
1051 objects, or a TypeError is raised. None of the keys in 'properties'
1052 may collide with the names of existing properties, or a ValueError
1053 is raised before any properties have been added.
1054 """
1055 for key in properties.keys():
1056 if self.properties.has_key(key):
1057 raise ValueError, key
1058 self.properties.update(properties)
1060 # XXX not in spec
1061 class Node:
1062 ''' A convenience wrapper for the given node
1063 '''
1064 def __init__(self, cl, nodeid, cache=1):
1065 self.__dict__['cl'] = cl
1066 self.__dict__['nodeid'] = nodeid
1067 self.__dict__['cache'] = cache
1068 def keys(self, protected=1):
1069 return self.cl.getprops(protected=protected).keys()
1070 def values(self, protected=1):
1071 l = []
1072 for name in self.cl.getprops(protected=protected).keys():
1073 l.append(self.cl.get(self.nodeid, name, cache=self.cache))
1074 return l
1075 def items(self, protected=1):
1076 l = []
1077 for name in self.cl.getprops(protected=protected).keys():
1078 l.append((name, self.cl.get(self.nodeid, name, cache=self.cache)))
1079 return l
1080 def has_key(self, name):
1081 return self.cl.getprops().has_key(name)
1082 def __getattr__(self, name):
1083 if self.__dict__.has_key(name):
1084 return self.__dict__[name]
1085 try:
1086 return self.cl.get(self.nodeid, name, cache=self.cache)
1087 except KeyError, value:
1088 # we trap this but re-raise it as AttributeError - all other
1089 # exceptions should pass through untrapped
1090 pass
1091 # nope, no such attribute
1092 raise AttributeError, str(value)
1093 def __getitem__(self, name):
1094 return self.cl.get(self.nodeid, name, cache=self.cache)
1095 def __setattr__(self, name, value):
1096 try:
1097 return self.cl.set(self.nodeid, **{name: value})
1098 except KeyError, value:
1099 raise AttributeError, str(value)
1100 def __setitem__(self, name, value):
1101 self.cl.set(self.nodeid, **{name: value})
1102 def history(self):
1103 return self.cl.history(self.nodeid)
1104 def retire(self):
1105 return self.cl.retire(self.nodeid)
1108 def Choice(name, db, *options):
1109 '''Quick helper to create a simple class with choices
1110 '''
1111 cl = Class(db, name, name=String(), order=String())
1112 for i in range(len(options)):
1113 cl.create(name=options[i], order=i)
1114 return hyperdb.Link(name)
1116 #
1117 # $Log: not supported by cvs2svn $
1118 # Revision 1.60 2002/04/03 05:54:31 richard
1119 # Fixed serialisation problem by moving the serialisation step out of the
1120 # hyperdb.Class (get, set) into the hyperdb.Database.
1121 #
1122 # Also fixed htmltemplate after the showid changes I made yesterday.
1123 #
1124 # Unit tests for all of the above written.
1125 #
1126 # Revision 1.59 2002/03/12 22:52:26 richard
1127 # more pychecker warnings removed
1128 #
1129 # Revision 1.58 2002/02/27 03:23:16 richard
1130 # Ran it through pychecker, made fixes
1131 #
1132 # Revision 1.57 2002/02/20 05:23:24 richard
1133 # Didn't accomodate new values for new properties
1134 #
1135 # Revision 1.56 2002/02/20 05:05:28 richard
1136 # . Added simple editing for classes that don't define a templated interface.
1137 # - access using the admin "class list" interface
1138 # - limited to admin-only
1139 # - requires the csv module from object-craft (url given if it's missing)
1140 #
1141 # Revision 1.55 2002/02/15 07:27:12 richard
1142 # Oops, precedences around the way w0rng.
1143 #
1144 # Revision 1.54 2002/02/15 07:08:44 richard
1145 # . Alternate email addresses are now available for users. See the MIGRATION
1146 # file for info on how to activate the feature.
1147 #
1148 # Revision 1.53 2002/01/22 07:21:13 richard
1149 # . fixed back_bsddb so it passed the journal tests
1150 #
1151 # ... it didn't seem happy using the back_anydbm _open method, which is odd.
1152 # Yet another occurrance of whichdb not being able to recognise older bsddb
1153 # databases. Yadda yadda. Made the HYPERDBDEBUG stuff more sane in the
1154 # process.
1155 #
1156 # Revision 1.52 2002/01/21 16:33:19 rochecompaan
1157 # You can now use the roundup-admin tool to pack the database
1158 #
1159 # Revision 1.51 2002/01/21 03:01:29 richard
1160 # brief docco on the do_journal argument
1161 #
1162 # Revision 1.50 2002/01/19 13:16:04 rochecompaan
1163 # Journal entries for link and multilink properties can now be switched on
1164 # or off.
1165 #
1166 # Revision 1.49 2002/01/16 07:02:57 richard
1167 # . lots of date/interval related changes:
1168 # - more relaxed date format for input
1169 #
1170 # Revision 1.48 2002/01/14 06:32:34 richard
1171 # . #502951 ] adding new properties to old database
1172 #
1173 # Revision 1.47 2002/01/14 02:20:15 richard
1174 # . changed all config accesses so they access either the instance or the
1175 # config attriubute on the db. This means that all config is obtained from
1176 # instance_config instead of the mish-mash of classes. This will make
1177 # switching to a ConfigParser setup easier too, I hope.
1178 #
1179 # At a minimum, this makes migration a _little_ easier (a lot easier in the
1180 # 0.5.0 switch, I hope!)
1181 #
1182 # Revision 1.46 2002/01/07 10:42:23 richard
1183 # oops
1184 #
1185 # Revision 1.45 2002/01/02 04:18:17 richard
1186 # hyperdb docstrings
1187 #
1188 # Revision 1.44 2002/01/02 02:31:38 richard
1189 # Sorry for the huge checkin message - I was only intending to implement #496356
1190 # but I found a number of places where things had been broken by transactions:
1191 # . modified ROUNDUPDBSENDMAILDEBUG to be SENDMAILDEBUG and hold a filename
1192 # for _all_ roundup-generated smtp messages to be sent to.
1193 # . the transaction cache had broken the roundupdb.Class set() reactors
1194 # . newly-created author users in the mailgw weren't being committed to the db
1195 #
1196 # Stuff that made it into CHANGES.txt (ie. the stuff I was actually working
1197 # on when I found that stuff :):
1198 # . #496356 ] Use threading in messages
1199 # . detectors were being registered multiple times
1200 # . added tests for mailgw
1201 # . much better attaching of erroneous messages in the mail gateway
1202 #
1203 # Revision 1.43 2001/12/20 06:13:24 rochecompaan
1204 # Bugs fixed:
1205 # . Exception handling in hyperdb for strings-that-look-like numbers got
1206 # lost somewhere
1207 # . Internet Explorer submits full path for filename - we now strip away
1208 # the path
1209 # Features added:
1210 # . Link and multilink properties are now displayed sorted in the cgi
1211 # interface
1212 #
1213 # Revision 1.42 2001/12/16 10:53:37 richard
1214 # take a copy of the node dict so that the subsequent set
1215 # operation doesn't modify the oldvalues structure
1216 #
1217 # Revision 1.41 2001/12/15 23:47:47 richard
1218 # Cleaned up some bare except statements
1219 #
1220 # Revision 1.40 2001/12/14 23:42:57 richard
1221 # yuck, a gdbm instance tests false :(
1222 # I've left the debugging code in - it should be removed one day if we're ever
1223 # _really_ anal about performace :)
1224 #
1225 # Revision 1.39 2001/12/02 05:06:16 richard
1226 # . We now use weakrefs in the Classes to keep the database reference, so
1227 # the close() method on the database is no longer needed.
1228 # I bumped the minimum python requirement up to 2.1 accordingly.
1229 # . #487480 ] roundup-server
1230 # . #487476 ] INSTALL.txt
1231 #
1232 # I also cleaned up the change message / post-edit stuff in the cgi client.
1233 # There's now a clearly marked "TODO: append the change note" where I believe
1234 # the change note should be added there. The "changes" list will obviously
1235 # have to be modified to be a dict of the changes, or somesuch.
1236 #
1237 # More testing needed.
1238 #
1239 # Revision 1.38 2001/12/01 07:17:50 richard
1240 # . We now have basic transaction support! Information is only written to
1241 # the database when the commit() method is called. Only the anydbm
1242 # backend is modified in this way - neither of the bsddb backends have been.
1243 # The mail, admin and cgi interfaces all use commit (except the admin tool
1244 # doesn't have a commit command, so interactive users can't commit...)
1245 # . Fixed login/registration forwarding the user to the right page (or not,
1246 # on a failure)
1247 #
1248 # Revision 1.37 2001/11/28 21:55:35 richard
1249 # . login_action and newuser_action return values were being ignored
1250 # . Woohoo! Found that bloody re-login bug that was killing the mail
1251 # gateway.
1252 # (also a minor cleanup in hyperdb)
1253 #
1254 # Revision 1.36 2001/11/27 03:16:09 richard
1255 # Another place that wasn't handling missing properties.
1256 #
1257 # Revision 1.35 2001/11/22 15:46:42 jhermann
1258 # Added module docstrings to all modules.
1259 #
1260 # Revision 1.34 2001/11/21 04:04:43 richard
1261 # *sigh* more missing value handling
1262 #
1263 # Revision 1.33 2001/11/21 03:40:54 richard
1264 # more new property handling
1265 #
1266 # Revision 1.32 2001/11/21 03:11:28 richard
1267 # Better handling of new properties.
1268 #
1269 # Revision 1.31 2001/11/12 22:01:06 richard
1270 # Fixed issues with nosy reaction and author copies.
1271 #
1272 # Revision 1.30 2001/11/09 10:11:08 richard
1273 # . roundup-admin now handles all hyperdb exceptions
1274 #
1275 # Revision 1.29 2001/10/27 00:17:41 richard
1276 # Made Class.stringFind() do caseless matching.
1277 #
1278 # Revision 1.28 2001/10/21 04:44:50 richard
1279 # bug #473124: UI inconsistency with Link fields.
1280 # This also prompted me to fix a fairly long-standing usability issue -
1281 # that of being able to turn off certain filters.
1282 #
1283 # Revision 1.27 2001/10/20 23:44:27 richard
1284 # Hyperdatabase sorts strings-that-look-like-numbers as numbers now.
1285 #
1286 # Revision 1.26 2001/10/16 03:48:01 richard
1287 # admin tool now complains if a "find" is attempted with a non-link property.
1288 #
1289 # Revision 1.25 2001/10/11 00:17:51 richard
1290 # Reverted a change in hyperdb so the default value for missing property
1291 # values in a create() is None and not '' (the empty string.) This obviously
1292 # breaks CSV import/export - the string 'None' will be created in an
1293 # export/import operation.
1294 #
1295 # Revision 1.24 2001/10/10 03:54:57 richard
1296 # Added database importing and exporting through CSV files.
1297 # Uses the csv module from object-craft for exporting if it's available.
1298 # Requires the csv module for importing.
1299 #
1300 # Revision 1.23 2001/10/09 23:58:10 richard
1301 # Moved the data stringification up into the hyperdb.Class class' get, set
1302 # and create methods. This means that the data is also stringified for the
1303 # journal call, and removes duplication of code from the backends. The
1304 # backend code now only sees strings.
1305 #
1306 # Revision 1.22 2001/10/09 07:25:59 richard
1307 # Added the Password property type. See "pydoc roundup.password" for
1308 # implementation details. Have updated some of the documentation too.
1309 #
1310 # Revision 1.21 2001/10/05 02:23:24 richard
1311 # . roundup-admin create now prompts for property info if none is supplied
1312 # on the command-line.
1313 # . hyperdb Class getprops() method may now return only the mutable
1314 # properties.
1315 # . Login now uses cookies, which makes it a whole lot more flexible. We can
1316 # now support anonymous user access (read-only, unless there's an
1317 # "anonymous" user, in which case write access is permitted). Login
1318 # handling has been moved into cgi_client.Client.main()
1319 # . The "extended" schema is now the default in roundup init.
1320 # . The schemas have had their page headings modified to cope with the new
1321 # login handling. Existing installations should copy the interfaces.py
1322 # file from the roundup lib directory to their instance home.
1323 # . Incorrectly had a Bizar Software copyright on the cgitb.py module from
1324 # Ping - has been removed.
1325 # . Fixed a whole bunch of places in the CGI interface where we should have
1326 # been returning Not Found instead of throwing an exception.
1327 # . Fixed a deviation from the spec: trying to modify the 'id' property of
1328 # an item now throws an exception.
1329 #
1330 # Revision 1.20 2001/10/04 02:12:42 richard
1331 # Added nicer command-line item adding: passing no arguments will enter an
1332 # interactive more which asks for each property in turn. While I was at it, I
1333 # fixed an implementation problem WRT the spec - I wasn't raising a
1334 # ValueError if the key property was missing from a create(). Also added a
1335 # protected=boolean argument to getprops() so we can list only the mutable
1336 # properties (defaults to yes, which lists the immutables).
1337 #
1338 # Revision 1.19 2001/08/29 04:47:18 richard
1339 # Fixed CGI client change messages so they actually include the properties
1340 # changed (again).
1341 #
1342 # Revision 1.18 2001/08/16 07:34:59 richard
1343 # better CGI text searching - but hidden filter fields are disappearing...
1344 #
1345 # Revision 1.17 2001/08/16 06:59:58 richard
1346 # all searches use re now - and they're all case insensitive
1347 #
1348 # Revision 1.16 2001/08/15 23:43:18 richard
1349 # Fixed some isFooTypes that I missed.
1350 # Refactored some code in the CGI code.
1351 #
1352 # Revision 1.15 2001/08/12 06:32:36 richard
1353 # using isinstance(blah, Foo) now instead of isFooType
1354 #
1355 # Revision 1.14 2001/08/07 00:24:42 richard
1356 # stupid typo
1357 #
1358 # Revision 1.13 2001/08/07 00:15:51 richard
1359 # Added the copyright/license notice to (nearly) all files at request of
1360 # Bizar Software.
1361 #
1362 # Revision 1.12 2001/08/02 06:38:17 richard
1363 # Roundupdb now appends "mailing list" information to its messages which
1364 # include the e-mail address and web interface address. Templates may
1365 # override this in their db classes to include specific information (support
1366 # instructions, etc).
1367 #
1368 # Revision 1.11 2001/08/01 04:24:21 richard
1369 # mailgw was assuming certain properties existed on the issues being created.
1370 #
1371 # Revision 1.10 2001/07/30 02:38:31 richard
1372 # get() now has a default arg - for migration only.
1373 #
1374 # Revision 1.9 2001/07/29 09:28:23 richard
1375 # Fixed sorting by clicking on column headings.
1376 #
1377 # Revision 1.8 2001/07/29 08:27:40 richard
1378 # Fixed handling of passed-in values in form elements (ie. during a
1379 # drill-down)
1380 #
1381 # Revision 1.7 2001/07/29 07:01:39 richard
1382 # Added vim command to all source so that we don't get no steenkin' tabs :)
1383 #
1384 # Revision 1.6 2001/07/29 05:36:14 richard
1385 # Cleanup of the link label generation.
1386 #
1387 # Revision 1.5 2001/07/29 04:05:37 richard
1388 # Added the fabricated property "id".
1389 #
1390 # Revision 1.4 2001/07/27 06:25:35 richard
1391 # Fixed some of the exceptions so they're the right type.
1392 # Removed the str()-ification of node ids so we don't mask oopsy errors any
1393 # more.
1394 #
1395 # Revision 1.3 2001/07/27 05:17:14 richard
1396 # just some comments
1397 #
1398 # Revision 1.2 2001/07/22 12:09:32 richard
1399 # Final commit of Grande Splite
1400 #
1401 # Revision 1.1 2001/07/22 11:58:35 richard
1402 # More Grande Splite
1403 #
1404 #
1405 # vim: set filetype=python ts=4 sw=4 et si