Author: barry.warsaw
Date: Tue Mar 22 12:39:06 2005
New Revision: 60

Modified:
   trunk/mailman/src/mailman/database/schema.py
Log:
Added lots of comments for the tables in the schema.  Fixed some coding nits.
I also added a held_messages column to the MailingList -- this will be used
for messages that are held for administrator approval.



Modified: trunk/mailman/src/mailman/database/schema.py
==============================================================================
--- trunk/mailman/src/mailman/database/schema.py        (original)
+++ trunk/mailman/src/mailman/database/schema.py        Tue Mar 22 12:39:06 2005
@@ -56,157 +56,218 @@
 
 class MailingList(SQLObject):
     _cacheValue = False
-    # Attributes
-    # We used to have an "overrides" field that was a ForeignKey to
-    # the AttributeGroup table. No longer. Now the AttributeGroup that
-    # overrides the mailing list's attributes is the one with a name
-    # identical to the mailing list's name.
+    # We used to have an "overrides" field that was a ForeignKey to the
+    # AttributeGroup table.  No longer.  Now the AttributeGroup that overrides
+    # the list's style's attributes is the one with a name identical to the
+    # mailing list's name.
+    #
+    # The fully qualified name of the form: [EMAIL PROTECTED]  The first part
+    # is called the list nickname, and they may not contain @ characters.
     name                = UnicodeCol(alternateID=True)
+    # A longer, human readable description of the mailing list.  This can
+    # contain HTML.
     description         = ForeignKey('CachedLanguageText', default=None)
+    # List owners have all the rights (conferred to them by site and domain
+    # owners) to modify the mailing list's attributes.
     owners              = ForeignKey('Roster')
+    # List moderators can only approve/deny postings and subscription requests.
     moderators          = ForeignKey('Roster')
+    # This is when the list was created.
     creation_date       = DateTimeCol(default=datetime.datetime.now)
+    # The domain that the mailing list is linked to.
     domain              = ForeignKey('Domain')
+    # The roster of all the list's members.
     members             = ForeignKey('Roster')
+    # The next three fields contain the autoresponse text used when a message
+    # is sent to the list's posting address, the -owner address or the
+    # -request robot address, respectively.
     post_response       = ForeignKey('Autoresponse', default=None)
     owner_response      = ForeignKey('Autoresponse', default=None)
     request_response    = ForeignKey('Autoresponse', default=None)
+    # Every message approved for posting to the list ends up in the archive
+    # message collection.  This doesn't necessarily mean the message is
+    # accessible from the archive.
     archives            = ForeignKey('MessageCollection')
+    # Every message sent to the -owners address gets put in this message
+    # collection.  This way, no such message is ever lost
     owner_archives      = ForeignKey('MessageCollection')
+    # Held messages are put in this message collection, at least until the
+    # moderators dispose of them.
+    held_messages       = ForeignKey('MessageCollection', default=None)
+    # Every list has zero or one style associated with it.  The list's style
+    # provides defaults for all the list attributes, unless the owners have
+    # overridden specific attributes.
     list_style          = ForeignKey('ListStyle', default=None)
 
     def get_value(self, attribute_name):
-        """
-        Returns the value corresponding to a given attribute, as a string.
+        """Returns the value corresponding to a given attribute, as a string.
 
-        Returns None if no value can be found. (This will happen, for example,
-        if the attribute name is misspelled).
+        Returns None if no value can be found.  (This will happen, for
+        example, if the attribute name is misspelled).
         
-        Lookup on attribute_name is case-insensitive.
-
         Possible ideas for later improvements: convert the string to the
         appropriate type.
         """
-        result = None
         try:
             overrides = AttributeGroup.byCollection_name(self.name)
         except SQLObjectNotFound:
-            overrides = None
-        if overrides is not None:
+            pass
+        else:
             for value in overrides.values:
-                if attribute_name.lower() == value.name.lower():
-                    result = value.value
-                    break
-
-        # If nothing found in overrides, check style
-        if result is None:
-            style = self.list_style
-            if style is None:
-                result = Attribute.byName(attribute_name).default_value
-            else:
-                result = self.list_style.get_value(attribute_name)
-
-        return result
+                if attribute_name == value.name:
+                    return value.value
+        # Either there were no overrides, or the attribute was not found in
+        # the overrides.  Check the list style.
+        if self.list_style is None:
+            return Attribute.byName(attribute_name).default_value
+        return self.list_style.get_value(attribute_name)
 
     def get_attributes(self):
-        """
-        Returns all attributes and their values, as a dict.
-        """
+        """Returns all attributes and their values, as a dictionary."""
         result = self.list_style.get_attributes()
         # Then set overrides
         try:
             overrides = AttributeGroup.byCollection_name(self.name)
         except SQLObjectNotFound:
-            overrides = None
-        if overrides is not None:
+            pass
+        else:
             for attr in overrides.values:
                 result[attr.name] = attr.value
-        # We're done!
         return result
 
     def is_locked(self, attribute_name):
-        """
-        Return True if attribute_name is locked, i.e., we're not allowed to
+        """Return True if attribute_name is locked, i.e., we're not allowed to
         change it.
 
-        There are two places where at attribute can be locked: at the site-wide
-        level, and at the domain level.
+        There are two places where at attribute can be locked: at the
+        site-wide level, and at the domain level.
         """
         defaultgroup = AttributeGroup.byCollection_name('default')
         attrs = list(AttributeValue.select(
-            AND(AttributeValue.q.groupID == defaultgroup.id,
-                AttributeValue.q.name == attribute_name)))
-        if len(attrs) > 0:
-            if attrs[0].policy == 'LOCKED':
-                return True
+                        AND(AttributeValue.q.groupID == defaultgroup.id,
+                            AttributeValue.q.name == attribute_name)))
+        if attrs and attrs[0].policy == 'LOCKED':
+            return True
         domaingroup = AttributeGroup.byCollection_name(self.list_domain())
         attrs = list(AttributeValue.select(
-            AND(AttributeValue.q.groupID == domaingroup.id,
-                AttributeValue.q.name == attribute_name)))
-        if len(attrs) > 0:
-            if attrs[0].policy == 'LOCKED':
-                return True
+                        AND(AttributeValue.q.groupID == domaingroup.id,
+                            AttributeValue.q.name == attribute_name)))
+        if attrs and attrs[0].policy == 'LOCKED':
+            return True
         return False
 
     def list_domain(self):
-        """
-        Return the domain part of the list name.
-        """
-        if self.name.find('@') != -1:
-            listname, listdomain = self.name.split('@', 1)
-        else:
-            listname, listdomain = self.name, ''
-        return listdomain
+        """Return the domain part of the list name."""
+        parts = self.name.split('@', 1)
+        if len(parts) == 1:
+            return ''
+        return parts[1]
 
 
 
 class Domain(SQLObject):
     _cacheValue = False
-    # Attributes
+    # These values contain various host names for the domain.  The only
+    # required value is the mailhost, which is the host name part of the email
+    # address.  E.g. in [EMAIL PROTECTED], it's 'example.com'.  The other
+    # host names are required only if those interfaces are enabled.
     name        = UnicodeCol(alternateID=True)
     mailhost    = UnicodeCol()
     webhost     = UnicodeCol(default=None)
     newshost    = UnicodeCol(default=None)
     imaphost    = UnicodeCol(default=None)
+    # This is the list of domain owners.  They are responsible for the
+    # administration and configuration of the domain, and in the pecking order
+    # of permissions, they live between the site owners and the list owners.
     admins      = ForeignKey('Roster')
 
 
-
 class SiteInformation(SQLObject):
+    _cacheValue = False
+    # This is the list of site owners.  They have permission to do anything to
+    # any domain or list on the site.  They set up domains and grant
+    # permission to the domain owners to further configure and grant
+    # permissions to the list owners for lists under their domain.
     admins      = ForeignKey('Roster')
 
 
 
 class Roster(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # A roster is a list of email addresses, either directly or indirectly.
+    # Specifically, a roster is a collection of roster entries, but each
+    # entry can either be an email address or a roster reference.  Roster
+    # references point to another roster.  In this way, we support
+    # composability of rosters.
     entries         = MultipleJoin('RosterEntry', joinColumn='member_of_id')
 
 
 class RosterEntry(InheritableSQLObject):
     _cacheValue = False
-    # Attributes
+    # This is the "base class" for things that can live in a roster.  The
+    # member_of column is primarily for joining with the Roster container
+    # table/class.
     member_of   = ForeignKey('Roster')
 
 
+class RosterReference(RosterEntry):
+    _cacheValue     = False
+    _inheritable    = False
+    # Roster references point to other rosters.
+    roster          = ForeignKey('Roster')
+
+
 class EmailAddress(RosterEntry):
     _cacheValue     = False
     _inheritable    = False
-    # Attributes
+    # This is the basic knowledge about an email address in the system.  Every
+    # registered address is represented uniquely by one of these.  Each
+    # instance must contain the actual email address.
     address             = UnicodeCol()
+    # For members who have multiple registered email addresses attached to
+    # their account, this is the priority with which we will use the email
+    # address when contacting the member.  Lower numbers mean higher priority.
+    # So if a priority 0 address gets disabled by bounces, we can ballback to
+    # using addresses with higher priority numbers.
     priority            = IntCol(default=0)
-    #member_id
+    # Each address can be assigned an arbitrary label by the user.  This
+    # allows them to designate addresses as "Home", "Work", "School", or
+    # whatever.  The label is used in various u/i elements.
     label               = UnicodeCol(default=None)
+    # This is the real name associated with the email address.
     realname            = UnicodeCol(default=None)
+    # The timestamp of when the email address was registered with the system.
+    # Note that registration is different than validation.  When an email
+    # address is registered but not validated, we don't trust it, and we won't
+    # send list email to such addresses.  When an address is verified
+    # (probably through mail-back confirmation), we'll fill in a verification
+    # date and then we can send email to the address.
     registration_date   = DateTimeCol(default=datetime.datetime.now)
     verification_date   = DateTimeCol(default=None)
 
     def get_preference(self, preference, listname=None):
+        """Find a preference for the email address.
+
+        Users can set preferences which override the system defaults.  They
+        can do this either on a specific email address, or for individual
+        'subscriptions' (i.e. tied to a mailing list).  In either case this
+        method returns the most specific value for the preference, in order:
+        list-specific preference, general email address preference, preference
+        default.
+        """
         if not listname:
+            # Query to find all the list member preferences that match the
+            # address and no list.  By convention, these are the
+            # non-list-specific preferences for the email address.  The
+            # results will have one or no items in it.
             results = ListMemberPreferences.select(
                 AND(ListMemberPreferences.q.addressID == self.id,
                     ListMemberPreferences.q.mailing_listID == None))
         else:
+            # Query to find all the list member preferences that match the
+            # address and possibly the mailing list.  If the address has a
+            # list-specific preference set, then the results will have two
+            # items in it, otherwise it will have one or no items.
             mlist = MailingList.byName(listname)
             results = ListMemberPreferences.select(
                 AND(ListMemberPreferences.q.addressID == self.id,
@@ -215,10 +276,15 @@
         # Sort the rows so that NULLs are last, meaning that we want
         # subscription specific preferences to override address specific
         # preferences.  We can't trust SQL to do this for us, since that's
-        # dialect dependent behavior.
+        # dialect dependent behavior.  But preflist should have no more than
+        # two items in it, so this won't be too bad performance-wise.
         preflist = list(results)
         preflist.sort(key=operator.attrgetter('mailing_list'), reverse=True)
         for lmpref in preflist:
+            # Query for the preference value in the preference group matching
+            # the preference group from the results list above.  If the query
+            # returns some elements, the first one will be the preference
+            # value we're interested in.
             prefval = PreferenceValue.select(
                 AND(PreferenceValue.q.groupID == lmpref.group.id,
                     PreferenceValue.q.name == preference))
@@ -230,16 +296,12 @@
         return Preference.byName(preference).default_value
 
 
-class RosterReference(RosterEntry):
-    _cacheValue     = False
-    _inheritable    = False
-    # Attributes
-    roster          = ForeignKey('Roster')
-
-
 class RegisteredMember(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # The only additional thing a registered member has over an EmailAddress
+    # is a password.  Note that we only use this table when Mailman is
+    # managing accounts.  For accounts kept in external systems, there will be
+    # no entry in this table for the address.
     password        = UnicodeCol()
     addresses       = MultipleJoin('EmailAddress')
 
@@ -247,17 +309,26 @@
 
 class Preference(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # A user preference has a name, a type, and a default value.  Using this
+    # arrangement allows us to add preferences without having to change the
+    # schema.  Our preference type system is pretty simple.
     name            = UnicodeCol(alternateID=True)
-    type            = EnumCol(enumValues=['TEXT',       'NUMBER',
-                                          'DATETIME',   'BOOL',
-                                          ])
+    type            = EnumCol(enumValues=
+                              ['TEXT', 'NUMBER', 'DATETIME', 'BOOL'])
+    # Default values are always kept in the database as strings.  While this
+    # is not ideal, it allows us to add preferences arbitrarily.  The type
+    # field above lets the system convert from strings to and from their
+    # native Python types.  Higher levels of the system should never see the
+    # raw strings (except of course for TEXT type preferences).
     default_value   = UnicodeCol()
 
 
 class PreferenceValue(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # Preference values are those that are set by a user somehow.  Otherwise
+    # the preference's default_value would be used.  Every preference value
+    # must belong to a preference group.  The name here must match a name in
+    # the Preferences table above.
     name            = UnicodeCol()
     group           = ForeignKey('PreferenceGroup')
     value           = UnicodeCol()
@@ -265,13 +336,19 @@
 
 class PreferenceGroup(SQLObject):    
     _cacheValue     = False
-    # Attributes
+    # This is the way preferences are grouped together, either for an email
+    # address, for for a membership (i.e. a subscription to a mailing list).
     preferences     = MultipleJoin('PreferenceValue', joinColumn='group_id')
 
 
 class ListMemberPreferences(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # While addresses can have preferences which specify general information,
+    # users can specifically override preferences for individual list
+    # memberships.  For example, they might set vacation for an email address
+    # across all lists they are subscribed to, but they may want to subscribe
+    # via digests to one list and via normal delivery for another.  This
+    # latter preference would be handled by a ListMemberPreference.
     mailing_list    = ForeignKey('MailingList', default=None)
     address         = ForeignKey('EmailAddress')
     group           = ForeignKey('PreferenceGroup')
@@ -280,14 +357,29 @@
 
 class Autoresponse(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # Autoresponses are those texts which are sent in response to a list
+    # posting, a -request message, or a message to the -owners.  Each
+    # autoresponse has a grace period, during which we will not resend the
+    # response text.  Response texts can be in any supported language
     graceperiod     = IntCol(default=90*24*60*60) # seconds, FIXME
     response_text   = ForeignKey('CachedLanguageText')
 
 
 class CachedLanguageText(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # This table represents any human readable text for a mailing list, such
+    # as the welcome message or an autoresponse message..  Its purpose is
+    # two-fold.  First, a list owner might want to set different texts for
+    # different language, so that members will see responses in their native
+    # language (for multiple language lists).  Second, a list owner might want
+    # to manage such texts in an external content management system, for
+    # example, to version control the texts.
+    #
+    # Using this class, the owner could specify an external http url for the
+    # text (for example), and Mailman will fetch the text when necessary, or
+    # when the cache lifetime for the text has expired.  Don't worry, Mailman
+    # will support 'internal' urls for text so that the traditional fill-in-
+    # a-text-field use case is still supported.
     for_language    = UnicodeCol()
     url             = UnicodeCol()
     last_cached     = DateTimeCol(default=None)
@@ -298,7 +390,12 @@
 
 class BounceInfo(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # Traditional, Mailman 2 style bounce information, tied to a specific
+    # email address.  Enhancements include the ability to associate a message
+    # collection with a bounce record, so that when (if) the user re-enables
+    # delivery, they can receive a list (or summary) of all the messages
+    # they've missed.  Also, bounce scores here are integers, so a MM2 score
+    # of 1.5 would translate into a score of 15 here.
     score               = IntCol(default=0)
     last_bounce_date    = DateTimeCol(default=None)
     notices_left        = IntCol(default=None)
@@ -310,7 +407,8 @@
 
 class Version(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # This table is primarily used to record the database schema number, for
+    # future upgrades.
     component       = UnicodeCol(alternateID=True)
     version         = UnicodeCol()
     build_number    = IntCol()
@@ -319,51 +417,69 @@
 
 class Message(SQLObject):
     _cacheValue         = False
-    # Message header attributes
+    # Mailman records every message that it sees -- or at least every approved
+    # message that it sees.  Messages live in message collections.  The first
+    # group of columns record metadata about the message that will be useful
+    # for archives, or other purposes.  They contain the contents from the
+    # corresponding RFC 2822 header.
+    #
+    # XXX should the actual contents of the message be stored in the database
+    # or some other place?
     header_message_id   = UnicodeCol(default=None)
     header_subject      = UnicodeCol(default=None)
     header_from         = UnicodeCol(default=None)
     header_date         = UnicodeCol(default=None)
     header_references   = UnicodeCol(default=None)
     header_in_reply_to  = UnicodeCol(default=None)
-    # Internal values
+    # This is the date that the Mailman server received the message.
     received_date       = DateTimeCol(default=datetime.datetime.now)
+    # The content_uri is a unique identifier assigned to the message.
+    #
     # XXX IWBNI we could make content_uri an alternate id, however that
     # requires that it not be NULL, otherwise you'll get an IntegrityError.
     # We're not yet sure whether we will be able to (or want to) calculate the
     # content_uri when we create the Message object.
     #
     # RFC 2369 defines the List-Archive: header, the content_uri should be a
-    # unique value, which combined with the List-Archive value could be used
-    # to fine the message.  content_uri should be calculable from some small
-    # subset of headers that are unlikely to be changed in transport.  That
-    # way any external system could arrive at the same content_uri knowing
-    # only the header of the message and the hash function.  Those headers (at
-    # least) should be stored in this table (see above).
+    # unique value, which when combined with the List-Archive value could be
+    # used to find the message.  content_uri should be calculable from some
+    # small subset of headers that are unlikely to be changed in transport.
+    # That way any external system could arrive at the same content_uri
+    # knowing only the header of the message and the hash function.  Those
+    # headers (at least) should be stored in this table (see above).
     content_uri         = UnicodeCol(default=None)
+    # All the message collections this message has been added to.
     collection          = RelatedJoin('MessageCollection')
 
 
 class MessageCollection(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # A collection of Message objects.
     messages        = RelatedJoin('Message')
 
 
 
 class Attribute(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # In a manner similar to user preferences, we define list configuration
+    # attributes such that we can change the set of attributes without having
+    # to change the schema.  This class contains the definition of all
+    # attributes, including their system default values.
     name            = UnicodeCol(alternateID=True)
-    type            = EnumCol(enumValues=['TEXT',       'NUMBER',
-                                          'DATETIME',   'BOOL',
-                                          ])
+    type            = EnumCol(enumValues=
+                              ['TEXT', 'NUMBER', 'DATETIME', 'BOOL'])
     default_value   = UnicodeCol()
     
 
 class AttributeGroup(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # As with preferences, attributes are contained in a group.  The primary
+    # difference though is that attribute groups can be partial and are
+    # named.  This allows us to use an attribute group as a partial list style
+    # specification, which might be named something like "Announce-only list"
+    # or "Digestable".  Thus only the attributes that correspond to the
+    # partial style are contained in this group, and groups are composable
+    # into list styles.
     collection_name = UnicodeCol(alternateID=True)
     list_styles     = RelatedJoin('ListStyle')
     values          = MultipleJoin('AttributeValue', joinColumn='group_id')
@@ -371,83 +487,84 @@
 
 class AttributeValue(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # The value of a particular attribute.
     name            = UnicodeCol()
     group           = ForeignKey('AttributeGroup')
     value           = UnicodeCol()
+    # This is also different than preferences.  Attributes have a policy
+    # assigned to them from the site and domain owners.  A locked attribute
+    # cannot be changed by people with less privilege.  An advanced attribute
+    # won't be displayed to a list owner unless they click on the 'advanced'
+    # link or button.  Basic attributes are those that a list owner will
+    # typically have to customize.
+    #
+    # XXX Do we need to record /who/ locked the attribute?  Otherwise how do
+    # we know that something was locked by the site owners vs. something that
+    # was locked by the domain owners?
     policy          = EnumCol(enumValues=['LOCKED', 'ADVANCED', 'BASIC'])
 
 
 class ListStyle(SQLObject):
     _cacheValue     = False
-    # Attributes
+    # A list style is a collection of attribute group, given a name.  This
+    # lets lists be created simply via template, and if the list hasn't
+    # overridden values in a list style (that the owners have permission to
+    # change), then the attribute value is inherited from the list style.
     name            = UnicodeCol(alternateID=True)
     groups          = RelatedJoin('AttributeGroup')
 
     def get_value(self, attribute_name):
-        """
-        Returns the value corresponding to a given attribute, as a string.
+        """Returns the value corresponding to a given attribute, as a string.
 
         Returns None if no value can be found. (This will happen, for example,
         if the attribute name is misspelled).
         
-        Lookup on attribute_name is case-insensitive.
-
         Possible ideas for later improvements: convert the string to the
         appropriate type.
         """
-        result = None
+        # See if the value has been specified in one of the list's attribute
+        # groups, and return it if so.
         for group in self.groups:
             for value in group.values:
-                if attribute_name.lower() == value.name.lower():
-                    result = value.value
-                    break
-            if result is not None:
-                break
-
-        # check for values associated with domain
-        ld = self.list_domain()
-        if result is None and ld:
-            result = ListStyle.byName(ld).get_value(attribute_name)
-
-        # still nothing found, lookup "glabal" default for attribute
-        if result is None:
-            attr = Attribute.byName(attribute_name)  # XXX Need test: what 
happens if attribute doesn't exist? I believe it raises SQLObjectNotFound.
-            if attr is None:
-                result = None
-            else:
-                result = attr.default_value
-
-        return result
+                if attribute_name == value.name:
+                    return value.value
+        # See if the value  is associated with domain.
+        domain = self.list_domain()
+        if domain:
+            result = ListStyle.byName(domain).get_value(attribute_name)
+            if result:
+                return result
+        # Still no attribute value was found, so look up the 'global' default
+        # value for the attribute.  XXX Need test: what happens if attribute
+        # doesn't exist? I believe it raises SQLObjectNotFound.
+        attr = Attribute.byName(attribute_name)
+        if attr is None:
+            return None
+        return attr.default_value
 
     def get_attributes(self):
-        """
-        Returns all attributes and their values, as a dict.
-        """
+        """Returns all attributes and their values, as a dictionary."""
         result = {}
-        # First set defaults
+        # First, get the defaults.
         for attr in Attribute.select():
             result[attr.name] = attr.default_value
-        # Now update with the values from our style
+        # Now update with the values from our style.
         for group in self.groups:
             for value in group.values:
                 result[value.name] = value.value
-        # We're done!
         return result
 
     def list_domain(self):
-        """
-        Return domain if this list style is for a mailing list, empty string
-        otherwise.
+        """Return domain if this list style is for a mailing list, empty
+        string otherwise.
 
-        For example, if this ListStyle is for [EMAIL PROTECTED], this 
-        will return "lists.com"
+        For example, if this ListStyle is for [EMAIL PROTECTED], this 
+        will return 'example.com'
         """
         try:
-            domain = self.name.split("@", 1)[1]
+            return self.name.split("@", 1)[1]
         except IndexError:
-            domain = ""
-        return domain
+            return ''
 
 # XXX For performance reasons, because these tables are so normalized, we
 # could generate a lookup table which will only change when an attribute has
_______________________________________________
Mailman-checkins mailing list
[email protected]
Unsubscribe: 
http://mail.python.org/mailman/options/mailman-checkins/archive%40jab.org

Reply via email to