Code

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