Code

. Alternate email addresses are now available for users. See the MIGRATION
[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.54 2002-02-15 07:08:44 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         for key, value in propvalues.items():
494             # check to make sure we're not duplicating an existing key
495             if key == self.key and node[key] != value:
496                 try:
497                     self.lookup(value)
498                 except KeyError:
499                     pass
500                 else:
501                     raise ValueError, 'node with key "%s" exists'%value
503             # this will raise the KeyError if the property isn't valid
504             # ... we don't use getprops() here because we only care about
505             # the writeable properties.
506             prop = self.properties[key]
508             if isinstance(prop, Link):
509                 link_class = self.properties[key].classname
510                 # if it isn't a number, it's a key
511                 if type(value) != type(''):
512                     raise ValueError, 'link value must be String'
513                 if not num_re.match(value):
514                     try:
515                         value = self.db.classes[link_class].lookup(value)
516                     except (TypeError, KeyError):
517                         raise IndexError, 'new property "%s": %s not a %s'%(
518                             key, value, self.properties[key].classname)
520                 if not self.db.hasnode(link_class, value):
521                     raise IndexError, '%s has no node %s'%(link_class, value)
523                 if self.properties[key].do_journal:
524                     # register the unlink with the old linked node
525                     if node[key] is not None:
526                         self.db.addjournal(link_class, node[key], 'unlink',
527                             (self.classname, nodeid, key))
529                     # register the link with the newly linked node
530                     if value is not None:
531                         self.db.addjournal(link_class, value, 'link',
532                             (self.classname, nodeid, key))
534             elif isinstance(prop, Multilink):
535                 if type(value) != type([]):
536                     raise TypeError, 'new property "%s" not a list of ids'%key
537                 link_class = self.properties[key].classname
538                 l = []
539                 for entry in value:
540                     # if it isn't a number, it's a key
541                     if type(entry) != type(''):
542                         raise ValueError, 'link value must be String'
543                     if not num_re.match(entry):
544                         try:
545                             entry = self.db.classes[link_class].lookup(entry)
546                         except (TypeError, KeyError):
547                             raise IndexError, 'new property "%s": %s not a %s'%(
548                                 key, entry, self.properties[key].classname)
549                     l.append(entry)
550                 value = l
551                 propvalues[key] = value
553                 # handle removals
554                 if node.has_key(key):
555                     l = node[key]
556                 else:
557                     l = []
558                 for id in l[:]:
559                     if id in value:
560                         continue
561                     # register the unlink with the old linked node
562                     if self.properties[key].do_journal:
563                         self.db.addjournal(link_class, id, 'unlink',
564                             (self.classname, nodeid, key))
565                     l.remove(id)
567                 # handle additions
568                 for id in value:
569                     if not self.db.hasnode(link_class, id):
570                         raise IndexError, '%s has no node %s'%(
571                             link_class, id)
572                     if id in l:
573                         continue
574                     # register the link with the newly linked node
575                     if self.properties[key].do_journal:
576                         self.db.addjournal(link_class, id, 'link',
577                             (self.classname, nodeid, key))
578                     l.append(id)
580             elif isinstance(prop, String):
581                 if value is not None and type(value) != type(''):
582                     raise TypeError, 'new property "%s" not a string'%key
584             elif isinstance(prop, Password):
585                 if not isinstance(value, password.Password):
586                     raise TypeError, 'new property "%s" not a Password'% key
587                 propvalues[key] = value = str(value)
589             elif value is not None and isinstance(prop, Date):
590                 if not isinstance(value, date.Date):
591                     raise TypeError, 'new property "%s" not a Date'% key
592                 propvalues[key] = value = value.get_tuple()
594             elif value is not None and isinstance(prop, Interval):
595                 if not isinstance(value, date.Interval):
596                     raise TypeError, 'new property "%s" not an Interval'% key
597                 propvalues[key] = value = value.get_tuple()
599             node[key] = value
601         self.db.setnode(self.classname, nodeid, node)
602         self.db.addjournal(self.classname, nodeid, 'set', propvalues)
604     def retire(self, nodeid):
605         """Retire a node.
606         
607         The properties on the node remain available from the get() method,
608         and the node's id is never reused.
609         
610         Retired nodes are not returned by the find(), list(), or lookup()
611         methods, and other nodes may reuse the values of their key properties.
612         """
613         if self.db.journaltag is None:
614             raise DatabaseError, 'Database open read-only'
615         node = self.db.getnode(self.classname, nodeid)
616         node[self.db.RETIRED_FLAG] = 1
617         self.db.setnode(self.classname, nodeid, node)
618         self.db.addjournal(self.classname, nodeid, 'retired', None)
620     def history(self, nodeid):
621         """Retrieve the journal of edits on a particular node.
623         'nodeid' must be the id of an existing node of this class or an
624         IndexError is raised.
626         The returned list contains tuples of the form
628             (date, tag, action, params)
630         'date' is a Timestamp object specifying the time of the change and
631         'tag' is the journaltag specified when the database was opened.
632         """
633         return self.db.getjournal(self.classname, nodeid)
635     # Locating nodes:
637     def setkey(self, propname):
638         """Select a String property of this class to be the key property.
640         'propname' must be the name of a String property of this class or
641         None, or a TypeError is raised.  The values of the key property on
642         all existing nodes must be unique or a ValueError is raised.
643         """
644         # TODO: validate that the property is a String!
645         self.key = propname
647     def getkey(self):
648         """Return the name of the key property for this class or None."""
649         return self.key
651     def labelprop(self, default_to_id=0):
652         ''' Return the property name for a label for the given node.
654         This method attempts to generate a consistent label for the node.
655         It tries the following in order:
656             1. key property
657             2. "name" property
658             3. "title" property
659             4. first property from the sorted property name list
660         '''
661         k = self.getkey()
662         if  k:
663             return k
664         props = self.getprops()
665         if props.has_key('name'):
666             return 'name'
667         elif props.has_key('title'):
668             return 'title'
669         if default_to_id:
670             return 'id'
671         props = props.keys()
672         props.sort()
673         return props[0]
675     # TODO: set up a separate index db file for this? profile?
676     def lookup(self, keyvalue):
677         """Locate a particular node by its key property and return its id.
679         If this class has no key property, a TypeError is raised.  If the
680         'keyvalue' matches one of the values for the key property among
681         the nodes in this class, the matching node's id is returned;
682         otherwise a KeyError is raised.
683         """
684         cldb = self.db.getclassdb(self.classname)
685         for nodeid in self.db.getnodeids(self.classname, cldb):
686             node = self.db.getnode(self.classname, nodeid, cldb)
687             if node.has_key(self.db.RETIRED_FLAG):
688                 continue
689             if node[self.key] == keyvalue:
690                 return nodeid
691         raise KeyError, keyvalue
693     # XXX: change from spec - allows multiple props to match
694     def find(self, **propspec):
695         """Get the ids of nodes in this class which link to a given node.
697         'propspec' consists of keyword args propname=nodeid   
698           'propname' must be the name of a property in this class, or a
699             KeyError is raised.  That property must be a Link or Multilink
700             property, or a TypeError is raised.
702           'nodeid' must be the id of an existing node in the class linked
703             to by the given property, or an IndexError is raised.
704         """
705         propspec = propspec.items()
706         for propname, nodeid in propspec:
707             # check the prop is OK
708             prop = self.properties[propname]
709             if not isinstance(prop, Link) and not isinstance(prop, Multilink):
710                 raise TypeError, "'%s' not a Link/Multilink property"%propname
711             if not self.db.hasnode(prop.classname, nodeid):
712                 raise ValueError, '%s has no node %s'%(prop.classname, nodeid)
714         # ok, now do the find
715         cldb = self.db.getclassdb(self.classname)
716         l = []
717         for id in self.db.getnodeids(self.classname, cldb):
718             node = self.db.getnode(self.classname, id, cldb)
719             if node.has_key(self.db.RETIRED_FLAG):
720                 continue
721             for propname, nodeid in propspec:
722                 property = node[propname]
723                 if isinstance(prop, Link) and nodeid == property:
724                     l.append(id)
725                 elif isinstance(prop, Multilink) and nodeid in property:
726                     l.append(id)
727         return l
729     def stringFind(self, **requirements):
730         """Locate a particular node by matching a set of its String
731         properties in a caseless search.
733         If the property is not a String property, a TypeError is raised.
734         
735         The return is a list of the id of all nodes that match.
736         """
737         for propname in requirements.keys():
738             prop = self.properties[propname]
739             if isinstance(not prop, String):
740                 raise TypeError, "'%s' not a String property"%propname
741             requirements[propname] = requirements[propname].lower()
742         l = []
743         cldb = self.db.getclassdb(self.classname)
744         for nodeid in self.db.getnodeids(self.classname, cldb):
745             node = self.db.getnode(self.classname, nodeid, cldb)
746             if node.has_key(self.db.RETIRED_FLAG):
747                 continue
748             for key, value in requirements.items():
749                 if node[key] and node[key].lower() != value:
750                     break
751             else:
752                 l.append(nodeid)
753         return l
755     def list(self):
756         """Return a list of the ids of the active nodes in this class."""
757         l = []
758         cn = self.classname
759         cldb = self.db.getclassdb(cn)
760         for nodeid in self.db.getnodeids(cn, cldb):
761             node = self.db.getnode(cn, nodeid, cldb)
762             if node.has_key(self.db.RETIRED_FLAG):
763                 continue
764             l.append(nodeid)
765         l.sort()
766         return l
768     # XXX not in spec
769     def filter(self, filterspec, sort, group, num_re = re.compile('^\d+$')):
770         ''' Return a list of the ids of the active nodes in this class that
771             match the 'filter' spec, sorted by the group spec and then the
772             sort spec
773         '''
774         cn = self.classname
776         # optimise filterspec
777         l = []
778         props = self.getprops()
779         for k, v in filterspec.items():
780             propclass = props[k]
781             if isinstance(propclass, Link):
782                 if type(v) is not type([]):
783                     v = [v]
784                 # replace key values with node ids
785                 u = []
786                 link_class =  self.db.classes[propclass.classname]
787                 for entry in v:
788                     if entry == '-1': entry = None
789                     elif not num_re.match(entry):
790                         try:
791                             entry = link_class.lookup(entry)
792                         except (TypeError,KeyError):
793                             raise ValueError, 'property "%s": %s not a %s'%(
794                                 k, entry, self.properties[k].classname)
795                     u.append(entry)
797                 l.append((0, k, u))
798             elif isinstance(propclass, Multilink):
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 not num_re.match(entry):
806                         try:
807                             entry = link_class.lookup(entry)
808                         except (TypeError,KeyError):
809                             raise ValueError, 'new property "%s": %s not a %s'%(
810                                 k, entry, self.properties[k].classname)
811                     u.append(entry)
812                 l.append((1, k, u))
813             elif isinstance(propclass, String):
814                 # simple glob searching
815                 v = re.sub(r'([\|\{\}\\\.\+\[\]\(\)])', r'\\\1', v)
816                 v = v.replace('?', '.')
817                 v = v.replace('*', '.*?')
818                 l.append((2, k, re.compile(v, re.I)))
819             else:
820                 l.append((6, k, v))
821         filterspec = l
823         # now, find all the nodes that are active and pass filtering
824         l = []
825         cldb = self.db.getclassdb(cn)
826         for nodeid in self.db.getnodeids(cn, cldb):
827             node = self.db.getnode(cn, nodeid, cldb)
828             if node.has_key(self.db.RETIRED_FLAG):
829                 continue
830             # apply filter
831             for t, k, v in filterspec:
832                 # this node doesn't have this property, so reject it
833                 if not node.has_key(k): break
835                 if t == 0 and node[k] not in v:
836                     # link - if this node'd property doesn't appear in the
837                     # filterspec's nodeid list, skip it
838                     break
839                 elif t == 1:
840                     # multilink - if any of the nodeids required by the
841                     # filterspec aren't in this node's property, then skip
842                     # it
843                     for value in v:
844                         if value not in node[k]:
845                             break
846                     else:
847                         continue
848                     break
849                 elif t == 2 and node[k] is None or not v.search(node[k]):
850                     # RE search
851                     break
852                 elif t == 6 and node[k] != v:
853                     # straight value comparison for the other types
854                     break
855             else:
856                 l.append((nodeid, node))
857         l.sort()
859         # optimise sort
860         m = []
861         for entry in sort:
862             if entry[0] != '-':
863                 m.append(('+', entry))
864             else:
865                 m.append((entry[0], entry[1:]))
866         sort = m
868         # optimise group
869         m = []
870         for entry in group:
871             if entry[0] != '-':
872                 m.append(('+', entry))
873             else:
874                 m.append((entry[0], entry[1:]))
875         group = m
876         # now, sort the result
877         def sortfun(a, b, sort=sort, group=group, properties=self.getprops(),
878                 db = self.db, cl=self):
879             a_id, an = a
880             b_id, bn = b
881             # sort by group and then sort
882             for list in group, sort:
883                 for dir, prop in list:
884                     # sorting is class-specific
885                     propclass = properties[prop]
887                     # handle the properties that might be "faked"
888                     # also, handle possible missing properties
889                     try:
890                         if not an.has_key(prop):
891                             an[prop] = cl.get(a_id, prop)
892                         av = an[prop]
893                     except KeyError:
894                         # the node doesn't have a value for this property
895                         if isinstance(propclass, Multilink): av = []
896                         else: av = ''
897                     try:
898                         if not bn.has_key(prop):
899                             bn[prop] = cl.get(b_id, prop)
900                         bv = bn[prop]
901                     except KeyError:
902                         # the node doesn't have a value for this property
903                         if isinstance(propclass, Multilink): bv = []
904                         else: bv = ''
906                     # String and Date values are sorted in the natural way
907                     if isinstance(propclass, String):
908                         # clean up the strings
909                         if av and av[0] in string.uppercase:
910                             av = an[prop] = av.lower()
911                         if bv and bv[0] in string.uppercase:
912                             bv = bn[prop] = bv.lower()
913                     if (isinstance(propclass, String) or
914                             isinstance(propclass, Date)):
915                         # it might be a string that's really an integer
916                         try:
917                             av = int(av)
918                             bv = int(bv)
919                         except:
920                             pass
921                         if dir == '+':
922                             r = cmp(av, bv)
923                             if r != 0: return r
924                         elif dir == '-':
925                             r = cmp(bv, av)
926                             if r != 0: return r
928                     # Link properties are sorted according to the value of
929                     # the "order" property on the linked nodes if it is
930                     # present; or otherwise on the key string of the linked
931                     # nodes; or finally on  the node ids.
932                     elif isinstance(propclass, Link):
933                         link = db.classes[propclass.classname]
934                         if av is None and bv is not None: return -1
935                         if av is not None and bv is None: return 1
936                         if av is None and bv is None: continue
937                         if link.getprops().has_key('order'):
938                             if dir == '+':
939                                 r = cmp(link.get(av, 'order'),
940                                     link.get(bv, 'order'))
941                                 if r != 0: return r
942                             elif dir == '-':
943                                 r = cmp(link.get(bv, 'order'),
944                                     link.get(av, 'order'))
945                                 if r != 0: return r
946                         elif link.getkey():
947                             key = link.getkey()
948                             if dir == '+':
949                                 r = cmp(link.get(av, key), link.get(bv, key))
950                                 if r != 0: return r
951                             elif dir == '-':
952                                 r = cmp(link.get(bv, key), link.get(av, key))
953                                 if r != 0: return r
954                         else:
955                             if dir == '+':
956                                 r = cmp(av, bv)
957                                 if r != 0: return r
958                             elif dir == '-':
959                                 r = cmp(bv, av)
960                                 if r != 0: return r
962                     # Multilink properties are sorted according to how many
963                     # links are present.
964                     elif isinstance(propclass, Multilink):
965                         if dir == '+':
966                             r = cmp(len(av), len(bv))
967                             if r != 0: return r
968                         elif dir == '-':
969                             r = cmp(len(bv), len(av))
970                             if r != 0: return r
971                 # end for dir, prop in list:
972             # end for list in sort, group:
973             # if all else fails, compare the ids
974             return cmp(a[0], b[0])
976         l.sort(sortfun)
977         return [i[0] for i in l]
979     def count(self):
980         """Get the number of nodes in this class.
982         If the returned integer is 'numnodes', the ids of all the nodes
983         in this class run from 1 to numnodes, and numnodes+1 will be the
984         id of the next node to be created in this class.
985         """
986         return self.db.countnodes(self.classname)
988     # Manipulating properties:
990     def getprops(self, protected=1):
991         """Return a dictionary mapping property names to property objects.
992            If the "protected" flag is true, we include protected properties -
993            those which may not be modified."""
994         d = self.properties.copy()
995         if protected:
996             d['id'] = String()
997         return d
999     def addprop(self, **properties):
1000         """Add properties to this class.
1002         The keyword arguments in 'properties' must map names to property
1003         objects, or a TypeError is raised.  None of the keys in 'properties'
1004         may collide with the names of existing properties, or a ValueError
1005         is raised before any properties have been added.
1006         """
1007         for key in properties.keys():
1008             if self.properties.has_key(key):
1009                 raise ValueError, key
1010         self.properties.update(properties)
1013 # XXX not in spec
1014 class Node:
1015     ''' A convenience wrapper for the given node
1016     '''
1017     def __init__(self, cl, nodeid, cache=1):
1018         self.__dict__['cl'] = cl
1019         self.__dict__['nodeid'] = nodeid
1020         self.__dict__['cache'] = cache
1021     def keys(self, protected=1):
1022         return self.cl.getprops(protected=protected).keys()
1023     def values(self, protected=1):
1024         l = []
1025         for name in self.cl.getprops(protected=protected).keys():
1026             l.append(self.cl.get(self.nodeid, name, cache=self.cache))
1027         return l
1028     def items(self, protected=1):
1029         l = []
1030         for name in self.cl.getprops(protected=protected).keys():
1031             l.append((name, self.cl.get(self.nodeid, name, cache=self.cache)))
1032         return l
1033     def has_key(self, name):
1034         return self.cl.getprops().has_key(name)
1035     def __getattr__(self, name):
1036         if self.__dict__.has_key(name):
1037             return self.__dict__[name]
1038         try:
1039             return self.cl.get(self.nodeid, name, cache=self.cache)
1040         except KeyError, value:
1041             # we trap this but re-raise it as AttributeError - all other
1042             # exceptions should pass through untrapped
1043             pass
1044         # nope, no such attribute
1045         raise AttributeError, str(value)
1046     def __getitem__(self, name):
1047         return self.cl.get(self.nodeid, name, cache=self.cache)
1048     def __setattr__(self, name, value):
1049         try:
1050             return self.cl.set(self.nodeid, **{name: value})
1051         except KeyError, value:
1052             raise AttributeError, str(value)
1053     def __setitem__(self, name, value):
1054         self.cl.set(self.nodeid, **{name: value})
1055     def history(self):
1056         return self.cl.history(self.nodeid)
1057     def retire(self):
1058         return self.cl.retire(self.nodeid)
1061 def Choice(name, *options):
1062     cl = Class(db, name, name=hyperdb.String(), order=hyperdb.String())
1063     for i in range(len(options)):
1064         cl.create(name=option[i], order=i)
1065     return hyperdb.Link(name)
1068 # $Log: not supported by cvs2svn $
1069 # Revision 1.53  2002/01/22 07:21:13  richard
1070 # . fixed back_bsddb so it passed the journal tests
1072 # ... it didn't seem happy using the back_anydbm _open method, which is odd.
1073 # Yet another occurrance of whichdb not being able to recognise older bsddb
1074 # databases. Yadda yadda. Made the HYPERDBDEBUG stuff more sane in the
1075 # process.
1077 # Revision 1.52  2002/01/21 16:33:19  rochecompaan
1078 # You can now use the roundup-admin tool to pack the database
1080 # Revision 1.51  2002/01/21 03:01:29  richard
1081 # brief docco on the do_journal argument
1083 # Revision 1.50  2002/01/19 13:16:04  rochecompaan
1084 # Journal entries for link and multilink properties can now be switched on
1085 # or off.
1087 # Revision 1.49  2002/01/16 07:02:57  richard
1088 #  . lots of date/interval related changes:
1089 #    - more relaxed date format for input
1091 # Revision 1.48  2002/01/14 06:32:34  richard
1092 #  . #502951 ] adding new properties to old database
1094 # Revision 1.47  2002/01/14 02:20:15  richard
1095 #  . changed all config accesses so they access either the instance or the
1096 #    config attriubute on the db. This means that all config is obtained from
1097 #    instance_config instead of the mish-mash of classes. This will make
1098 #    switching to a ConfigParser setup easier too, I hope.
1100 # At a minimum, this makes migration a _little_ easier (a lot easier in the
1101 # 0.5.0 switch, I hope!)
1103 # Revision 1.46  2002/01/07 10:42:23  richard
1104 # oops
1106 # Revision 1.45  2002/01/02 04:18:17  richard
1107 # hyperdb docstrings
1109 # Revision 1.44  2002/01/02 02:31:38  richard
1110 # Sorry for the huge checkin message - I was only intending to implement #496356
1111 # but I found a number of places where things had been broken by transactions:
1112 #  . modified ROUNDUPDBSENDMAILDEBUG to be SENDMAILDEBUG and hold a filename
1113 #    for _all_ roundup-generated smtp messages to be sent to.
1114 #  . the transaction cache had broken the roundupdb.Class set() reactors
1115 #  . newly-created author users in the mailgw weren't being committed to the db
1117 # Stuff that made it into CHANGES.txt (ie. the stuff I was actually working
1118 # on when I found that stuff :):
1119 #  . #496356 ] Use threading in messages
1120 #  . detectors were being registered multiple times
1121 #  . added tests for mailgw
1122 #  . much better attaching of erroneous messages in the mail gateway
1124 # Revision 1.43  2001/12/20 06:13:24  rochecompaan
1125 # Bugs fixed:
1126 #   . Exception handling in hyperdb for strings-that-look-like numbers got
1127 #     lost somewhere
1128 #   . Internet Explorer submits full path for filename - we now strip away
1129 #     the path
1130 # Features added:
1131 #   . Link and multilink properties are now displayed sorted in the cgi
1132 #     interface
1134 # Revision 1.42  2001/12/16 10:53:37  richard
1135 # take a copy of the node dict so that the subsequent set
1136 # operation doesn't modify the oldvalues structure
1138 # Revision 1.41  2001/12/15 23:47:47  richard
1139 # Cleaned up some bare except statements
1141 # Revision 1.40  2001/12/14 23:42:57  richard
1142 # yuck, a gdbm instance tests false :(
1143 # I've left the debugging code in - it should be removed one day if we're ever
1144 # _really_ anal about performace :)
1146 # Revision 1.39  2001/12/02 05:06:16  richard
1147 # . We now use weakrefs in the Classes to keep the database reference, so
1148 #   the close() method on the database is no longer needed.
1149 #   I bumped the minimum python requirement up to 2.1 accordingly.
1150 # . #487480 ] roundup-server
1151 # . #487476 ] INSTALL.txt
1153 # I also cleaned up the change message / post-edit stuff in the cgi client.
1154 # There's now a clearly marked "TODO: append the change note" where I believe
1155 # the change note should be added there. The "changes" list will obviously
1156 # have to be modified to be a dict of the changes, or somesuch.
1158 # More testing needed.
1160 # Revision 1.38  2001/12/01 07:17:50  richard
1161 # . We now have basic transaction support! Information is only written to
1162 #   the database when the commit() method is called. Only the anydbm
1163 #   backend is modified in this way - neither of the bsddb backends have been.
1164 #   The mail, admin and cgi interfaces all use commit (except the admin tool
1165 #   doesn't have a commit command, so interactive users can't commit...)
1166 # . Fixed login/registration forwarding the user to the right page (or not,
1167 #   on a failure)
1169 # Revision 1.37  2001/11/28 21:55:35  richard
1170 #  . login_action and newuser_action return values were being ignored
1171 #  . Woohoo! Found that bloody re-login bug that was killing the mail
1172 #    gateway.
1173 #  (also a minor cleanup in hyperdb)
1175 # Revision 1.36  2001/11/27 03:16:09  richard
1176 # Another place that wasn't handling missing properties.
1178 # Revision 1.35  2001/11/22 15:46:42  jhermann
1179 # Added module docstrings to all modules.
1181 # Revision 1.34  2001/11/21 04:04:43  richard
1182 # *sigh* more missing value handling
1184 # Revision 1.33  2001/11/21 03:40:54  richard
1185 # more new property handling
1187 # Revision 1.32  2001/11/21 03:11:28  richard
1188 # Better handling of new properties.
1190 # Revision 1.31  2001/11/12 22:01:06  richard
1191 # Fixed issues with nosy reaction and author copies.
1193 # Revision 1.30  2001/11/09 10:11:08  richard
1194 #  . roundup-admin now handles all hyperdb exceptions
1196 # Revision 1.29  2001/10/27 00:17:41  richard
1197 # Made Class.stringFind() do caseless matching.
1199 # Revision 1.28  2001/10/21 04:44:50  richard
1200 # bug #473124: UI inconsistency with Link fields.
1201 #    This also prompted me to fix a fairly long-standing usability issue -
1202 #    that of being able to turn off certain filters.
1204 # Revision 1.27  2001/10/20 23:44:27  richard
1205 # Hyperdatabase sorts strings-that-look-like-numbers as numbers now.
1207 # Revision 1.26  2001/10/16 03:48:01  richard
1208 # admin tool now complains if a "find" is attempted with a non-link property.
1210 # Revision 1.25  2001/10/11 00:17:51  richard
1211 # Reverted a change in hyperdb so the default value for missing property
1212 # values in a create() is None and not '' (the empty string.) This obviously
1213 # breaks CSV import/export - the string 'None' will be created in an
1214 # export/import operation.
1216 # Revision 1.24  2001/10/10 03:54:57  richard
1217 # Added database importing and exporting through CSV files.
1218 # Uses the csv module from object-craft for exporting if it's available.
1219 # Requires the csv module for importing.
1221 # Revision 1.23  2001/10/09 23:58:10  richard
1222 # Moved the data stringification up into the hyperdb.Class class' get, set
1223 # and create methods. This means that the data is also stringified for the
1224 # journal call, and removes duplication of code from the backends. The
1225 # backend code now only sees strings.
1227 # Revision 1.22  2001/10/09 07:25:59  richard
1228 # Added the Password property type. See "pydoc roundup.password" for
1229 # implementation details. Have updated some of the documentation too.
1231 # Revision 1.21  2001/10/05 02:23:24  richard
1232 #  . roundup-admin create now prompts for property info if none is supplied
1233 #    on the command-line.
1234 #  . hyperdb Class getprops() method may now return only the mutable
1235 #    properties.
1236 #  . Login now uses cookies, which makes it a whole lot more flexible. We can
1237 #    now support anonymous user access (read-only, unless there's an
1238 #    "anonymous" user, in which case write access is permitted). Login
1239 #    handling has been moved into cgi_client.Client.main()
1240 #  . The "extended" schema is now the default in roundup init.
1241 #  . The schemas have had their page headings modified to cope with the new
1242 #    login handling. Existing installations should copy the interfaces.py
1243 #    file from the roundup lib directory to their instance home.
1244 #  . Incorrectly had a Bizar Software copyright on the cgitb.py module from
1245 #    Ping - has been removed.
1246 #  . Fixed a whole bunch of places in the CGI interface where we should have
1247 #    been returning Not Found instead of throwing an exception.
1248 #  . Fixed a deviation from the spec: trying to modify the 'id' property of
1249 #    an item now throws an exception.
1251 # Revision 1.20  2001/10/04 02:12:42  richard
1252 # Added nicer command-line item adding: passing no arguments will enter an
1253 # interactive more which asks for each property in turn. While I was at it, I
1254 # fixed an implementation problem WRT the spec - I wasn't raising a
1255 # ValueError if the key property was missing from a create(). Also added a
1256 # protected=boolean argument to getprops() so we can list only the mutable
1257 # properties (defaults to yes, which lists the immutables).
1259 # Revision 1.19  2001/08/29 04:47:18  richard
1260 # Fixed CGI client change messages so they actually include the properties
1261 # changed (again).
1263 # Revision 1.18  2001/08/16 07:34:59  richard
1264 # better CGI text searching - but hidden filter fields are disappearing...
1266 # Revision 1.17  2001/08/16 06:59:58  richard
1267 # all searches use re now - and they're all case insensitive
1269 # Revision 1.16  2001/08/15 23:43:18  richard
1270 # Fixed some isFooTypes that I missed.
1271 # Refactored some code in the CGI code.
1273 # Revision 1.15  2001/08/12 06:32:36  richard
1274 # using isinstance(blah, Foo) now instead of isFooType
1276 # Revision 1.14  2001/08/07 00:24:42  richard
1277 # stupid typo
1279 # Revision 1.13  2001/08/07 00:15:51  richard
1280 # Added the copyright/license notice to (nearly) all files at request of
1281 # Bizar Software.
1283 # Revision 1.12  2001/08/02 06:38:17  richard
1284 # Roundupdb now appends "mailing list" information to its messages which
1285 # include the e-mail address and web interface address. Templates may
1286 # override this in their db classes to include specific information (support
1287 # instructions, etc).
1289 # Revision 1.11  2001/08/01 04:24:21  richard
1290 # mailgw was assuming certain properties existed on the issues being created.
1292 # Revision 1.10  2001/07/30 02:38:31  richard
1293 # get() now has a default arg - for migration only.
1295 # Revision 1.9  2001/07/29 09:28:23  richard
1296 # Fixed sorting by clicking on column headings.
1298 # Revision 1.8  2001/07/29 08:27:40  richard
1299 # Fixed handling of passed-in values in form elements (ie. during a
1300 # drill-down)
1302 # Revision 1.7  2001/07/29 07:01:39  richard
1303 # Added vim command to all source so that we don't get no steenkin' tabs :)
1305 # Revision 1.6  2001/07/29 05:36:14  richard
1306 # Cleanup of the link label generation.
1308 # Revision 1.5  2001/07/29 04:05:37  richard
1309 # Added the fabricated property "id".
1311 # Revision 1.4  2001/07/27 06:25:35  richard
1312 # Fixed some of the exceptions so they're the right type.
1313 # Removed the str()-ification of node ids so we don't mask oopsy errors any
1314 # more.
1316 # Revision 1.3  2001/07/27 05:17:14  richard
1317 # just some comments
1319 # Revision 1.2  2001/07/22 12:09:32  richard
1320 # Final commit of Grande Splite
1322 # Revision 1.1  2001/07/22 11:58:35  richard
1323 # More Grande Splite
1326 # vim: set filetype=python ts=4 sw=4 et si