From 1341b9f00d56c806b78298f3dad7350d8fa28c39 Mon Sep 17 00:00:00 2001 From: Abhilash Raj Date: Fri, 5 Sep 2014 10:45:50 +0530 Subject: replace all storm types and relationships with sqlalchemy --- src/mailman/model/message.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'src/mailman/model/message.py') diff --git a/src/mailman/model/message.py b/src/mailman/model/message.py index 2d697c30b..64ee2c84a 100644 --- a/src/mailman/model/message.py +++ b/src/mailman/model/message.py @@ -24,7 +24,7 @@ __all__ = [ 'Message', ] -from storm.locals import AutoReload, Int, RawStr, Unicode +from sqlalchemy import Column, Integer, Unicode from zope.interface import implementer from mailman.database.model import Model @@ -37,10 +37,12 @@ from mailman.interfaces.messages import IMessage class Message(Model): """A message in the message store.""" - id = Int(primary=True, default=AutoReload) - message_id = Unicode() - message_id_hash = RawStr() - path = RawStr() + __tablename__ = 'message' + + id = Column(Integer, primary_key=True, default=AutoReload)) + message_id = Column(Unicode) + message_id_hash = Column(Unicode) + path = Column(Unicode) # TODO : was RawStr() # This is a Messge-ID field representation, not a database row id. @dbconnection -- cgit v1.2.3-70-g09d2 From db1f5638fe1ab83406a305c3f108c4a1bcfd9cd7 Mon Sep 17 00:00:00 2001 From: Abhilash Raj Date: Sat, 6 Sep 2014 15:43:47 +0530 Subject: * change declarative_base class to use ModelMeta class * update some queries to match SA style --- src/mailman/app/subscriptions.py | 2 +- src/mailman/database/base.py | 89 +++----------------------------------- src/mailman/database/factory.py | 2 +- src/mailman/database/model.py | 23 +++------- src/mailman/database/postgresql.py | 4 +- src/mailman/database/sqlite.py | 4 +- src/mailman/database/types.py | 5 ++- src/mailman/interfaces/database.py | 2 +- src/mailman/model/address.py | 5 ++- src/mailman/model/autorespond.py | 2 +- src/mailman/model/bounce.py | 2 +- src/mailman/model/digests.py | 2 +- src/mailman/model/domain.py | 10 ++--- src/mailman/model/listmanager.py | 22 +++++----- src/mailman/model/mailinglist.py | 23 ++++++---- src/mailman/model/member.py | 6 +-- src/mailman/model/message.py | 2 +- src/mailman/model/messagestore.py | 6 +-- src/mailman/model/mime.py | 4 +- src/mailman/model/pending.py | 10 +++-- src/mailman/model/preferences.py | 2 +- src/mailman/model/requests.py | 2 +- src/mailman/model/roster.py | 2 +- src/mailman/model/user.py | 10 +++-- src/mailman/model/version.py | 2 +- 25 files changed, 84 insertions(+), 159 deletions(-) (limited to 'src/mailman/model/message.py') diff --git a/src/mailman/app/subscriptions.py b/src/mailman/app/subscriptions.py index b2560beb5..d24a9a545 100644 --- a/src/mailman/app/subscriptions.py +++ b/src/mailman/app/subscriptions.py @@ -28,7 +28,7 @@ __all__ = [ from operator import attrgetter from passlib.utils import generate_password as generate -from storm.expr import And, Or +#from storm.expr import And, Or from uuid import UUID from zope.component import getUtility from zope.interface import implementer diff --git a/src/mailman/database/base.py b/src/mailman/database/base.py index 1577c981d..a2392bb3a 100644 --- a/src/mailman/database/base.py +++ b/src/mailman/database/base.py @@ -31,8 +31,6 @@ from lazr.config import as_boolean from pkg_resources import resource_listdir, resource_string from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker -from storm.cache import GenerationalCache -from storm.locals import create_database, Store from zope.interface import implementer from mailman.config import config @@ -54,7 +52,7 @@ class SABaseDatabase: """ TAG='' - def __inti__(self): + def __init__(self): self.url = None self.store = None @@ -70,56 +68,6 @@ class SABaseDatabase: def _prepare(self, url): pass - def initialize(Self, debug=None): - url = expand(config.database.url, config.paths) - log.debug('Database url: %s', url) - self.url = url - self._prepare(url) - engine = create_engine(url) - Session = sessionmaker(bind=engine) - store = Session() - self.store = session() - store.commit() - - -@implementer(IDatabase) -class StormBaseDatabase: - """The database base class for use with the Storm ORM. - - Use this as a base class for your DB-specific derived classes. - """ - - # Tag used to distinguish the database being used. Override this in base - # classes. - TAG = '' - - def __init__(self): - self.url = None - self.store = None - - def begin(self): - """See `IDatabase`.""" - # Storm takes care of this for us. - pass - - def commit(self): - """See `IDatabase`.""" - self.store.commit() - - def abort(self): - """See `IDatabase`.""" - self.store.rollback() - - def _database_exists(self): - """Return True if the database exists and is initialized. - - Return False when Mailman needs to create and initialize the - underlying database schema. - - Base classes *must* override this. - """ - raise NotImplementedError - def _pre_reset(self, store): """Clean up method for testing. @@ -137,41 +85,14 @@ class StormBaseDatabase: database-specific post-removal cleanup. """ pass - - def _prepare(self, url): - """Prepare the database for creation. - - Some database backends need to do so me prep work before letting Storm - create the database. For example, we have to touch the SQLite .db - file first so that it has the proper file modes. - """ - pass - def initialize(self, debug=None): - """See `IDatabase`.""" - # Calculate the engine url. url = expand(config.database.url, config.paths) log.debug('Database url: %s', url) - # XXX By design of SQLite, database file creation does not honor - # umask. See their ticket #1193: - # http://www.sqlite.org/cvstrac/tktview?tn=1193,31 - # - # This sucks for us because the mailman.db file /must/ be group - # writable, however even though we guarantee our umask is 002 here, it - # still gets created without the necessary g+w permission, due to - # SQLite's policy. This should only affect SQLite engines because its - # the only one that creates a little file on the local file system. - # This kludges around their bug by "touch"ing the database file before - # SQLite has any chance to create it, thus honoring the umask and - # ensuring the right permissions. We only try to do this for SQLite - # engines, and yes, we could have chmod'd the file after the fact, but - # half dozen and all... self.url = url self._prepare(url) - database = create_database(url) - store = Store(database, GenerationalCache()) - database.DEBUG = (as_boolean(config.database.debug) - if debug is None else debug) + engine = create_engine(url) + Session = sessionmaker(bind=engine) + store = Session() self.store = store store.commit() @@ -262,6 +183,8 @@ class StormBaseDatabase: # Add a marker that indicates the migration version being applied. store.add(Version(component='schema', version=version)) + + @staticmethod def _make_temporary(): raise NotImplementedError diff --git a/src/mailman/database/factory.py b/src/mailman/database/factory.py index db453ea41..426d283e1 100644 --- a/src/mailman/database/factory.py +++ b/src/mailman/database/factory.py @@ -54,7 +54,7 @@ class DatabaseFactory: database = call_name(database_class) verifyObject(IDatabase, database) database.initialize() - database.load_migrations() + #database.load_migrations() database.commit() return database diff --git a/src/mailman/database/model.py b/src/mailman/database/model.py index 5fbf4005d..4b8478fc6 100644 --- a/src/mailman/database/model.py +++ b/src/mailman/database/model.py @@ -24,26 +24,21 @@ __all__ = [ 'Model', ] - from operator import attrgetter from sqlalchemy.ext.declarative import declarative_base -from storm.properties import PropertyPublisherMeta - -Base = declerative_base() - -class ModelMeta(PropertyPublisherMeta): +class ModelMeta(object): """Do more magic on table classes.""" _class_registry = set() def __init__(self, name, bases, dict): - # Before we let the base class do it's thing, force an __storm_table__ + # Before we let the base class do it's thing, force an __tablename__ # property to enforce our table naming convention. - self.__storm_table__ = name.lower() - super(ModelMeta, self).__init__(name, bases, dict) + self.__tablename__ = name.lower() + # super(ModelMeta, self).__init__(name, bases, dict) # Register the model class so that it can be more easily cleared. # This is required by the test framework so that the corresponding # table can be reset between tests. @@ -60,12 +55,8 @@ class ModelMeta(PropertyPublisherMeta): config.db._pre_reset(store) # Make sure this is deterministic, by sorting on the storm table name. classes = sorted(ModelMeta._class_registry, - key=attrgetter('__storm_table__')) + key=attrgetter('__tablename__')) for model_class in classes: - store.find(model_class).remove() - + store.query(model_class).delete() - -class Model: - """Like Storm's `Storm` subclass, but with a bit extra.""" - __metaclass__ = Base +Model = declarative_base(cls=ModelMeta) diff --git a/src/mailman/database/postgresql.py b/src/mailman/database/postgresql.py index 48c68a937..1ee454074 100644 --- a/src/mailman/database/postgresql.py +++ b/src/mailman/database/postgresql.py @@ -32,12 +32,12 @@ from functools import partial from operator import attrgetter from urlparse import urlsplit, urlunsplit -from mailman.database.base import StormBaseDatabase +from mailman.database.base import SABaseDatabase from mailman.testing.helpers import configuration -class PostgreSQLDatabase(StormBaseDatabase): +class PostgreSQLDatabase(SABaseDatabase): """Database class for PostgreSQL.""" TAG = 'postgres' diff --git a/src/mailman/database/sqlite.py b/src/mailman/database/sqlite.py index 15629615f..ec404b9c3 100644 --- a/src/mailman/database/sqlite.py +++ b/src/mailman/database/sqlite.py @@ -34,12 +34,12 @@ import tempfile from functools import partial from urlparse import urlparse -from mailman.database.base import StormBaseDatabase +from mailman.database.base import SABaseDatabase from mailman.testing.helpers import configuration -class SQLiteDatabase(StormBaseDatabase): +class SQLiteDatabase(SABaseDatabase): """Database class for SQLite.""" TAG = 'sqlite' diff --git a/src/mailman/database/types.py b/src/mailman/database/types.py index 5ffbf3965..045065591 100644 --- a/src/mailman/database/types.py +++ b/src/mailman/database/types.py @@ -23,13 +23,14 @@ from __future__ import absolute_import, print_function, unicode_literals __metaclass__ = type __all__ = [ 'Enum', - 'UUID' + 'UUID', ] import uuid +from sqlalchemy import Integer from sqlalchemy.types import TypeDecorator, BINARY, CHAR -from sqlalchemy.dailects import postgresql +from sqlalchemy.dialects import postgresql diff --git a/src/mailman/interfaces/database.py b/src/mailman/interfaces/database.py index 21f2f71d0..d8fde2b93 100644 --- a/src/mailman/interfaces/database.py +++ b/src/mailman/interfaces/database.py @@ -61,7 +61,7 @@ class IDatabase(Interface): """Abort the current transaction.""" store = Attribute( - """The underlying Storm store on which you can do queries.""") + """The underlying SQLAlchemy store on which you can do queries.""") diff --git a/src/mailman/model/address.py b/src/mailman/model/address.py index 88e28b919..59d54aab0 100644 --- a/src/mailman/model/address.py +++ b/src/mailman/model/address.py @@ -27,7 +27,7 @@ __all__ = [ from email.utils import formataddr from sqlalchemy import (Column, Integer, String, Unicode, - ForeignKey, Datetime) + ForeignKey, DateTime) from sqlalchemy.orm import relationship, backref from zope.component import getUtility from zope.event import notify @@ -50,10 +50,11 @@ class Address(Model): email = Column(Unicode) _original = Column(Unicode) display_name = Column(Unicode) - _verified_on = Column('verified_on', Datetime) + _verified_on = Column('verified_on', DateTime) registered_on = Column(DateTime) user_id = Column(Integer, ForeignKey('user.id')) + preferences_id = Column(Integer, ForeignKey('preferences.id')) prefereces = relationship('Preferences', backref=backref('Address', uselist=False)) diff --git a/src/mailman/model/autorespond.py b/src/mailman/model/autorespond.py index 4e1f42cca..92e0b6ebe 100644 --- a/src/mailman/model/autorespond.py +++ b/src/mailman/model/autorespond.py @@ -28,7 +28,7 @@ __all__ = [ from sqlalchemy import (Column, Integer, String, Unicode, ForeignKey, Date) -from storm.locals import And, Date, Desc, Int, Reference +from sqlalchemy.orm import relationship from zope.interface import implementer from mailman.database.model import Model diff --git a/src/mailman/model/bounce.py b/src/mailman/model/bounce.py index a40178837..b3f053cba 100644 --- a/src/mailman/model/bounce.py +++ b/src/mailman/model/bounce.py @@ -45,7 +45,7 @@ class BounceEvent(Model): __tablename__ = 'bounceevent' - id = Unicode(Integer, primary_key=True) + id = Column(Integer, primary_key=True) list_id = Column(Unicode) email = Column(Unicode) timestamp = Column(DateTime) diff --git a/src/mailman/model/digests.py b/src/mailman/model/digests.py index 0794bfb4f..e94bb073e 100644 --- a/src/mailman/model/digests.py +++ b/src/mailman/model/digests.py @@ -47,7 +47,7 @@ class OneLastDigest(Model): mailing_list_id = Column(Integer, ForeignKey('mailinglist.id')) maling_list = relationship('MailingList') - address_id = Columne(Integer, ForeignKey('address.id')) + address_id = Column(Integer, ForeignKey('address.id')) address = relationship('Address') delivery_mode = Column(Enum(enum=DeliveryMode)) diff --git a/src/mailman/model/domain.py b/src/mailman/model/domain.py index 2a5391abc..860107b15 100644 --- a/src/mailman/model/domain.py +++ b/src/mailman/model/domain.py @@ -142,14 +142,14 @@ class DomainManager: def remove(self, store, mail_host): domain = self[mail_host] notify(DomainDeletingEvent(domain)) - store.remove(domain) + store.delete(domain) notify(DomainDeletedEvent(mail_host)) return domain @dbconnection def get(self, store, mail_host, default=None): """See `IDomainManager`.""" - domains = store.find(Domain, mail_host=mail_host) + domains = store.query(Domain).filter_by(mail_host=mail_host) if domains.count() < 1: return default assert domains.count() == 1, ( @@ -166,15 +166,15 @@ class DomainManager: @dbconnection def __len__(self, store): - return store.find(Domain).count() + return store.query(Domain).count() @dbconnection def __iter__(self, store): """See `IDomainManager`.""" - for domain in store.find(Domain): + for domain in store.query(Domain).all(): yield domain @dbconnection def __contains__(self, store, mail_host): """See `IDomainManager`.""" - return store.find(Domain, mail_host=mail_host).count() > 0 + return store.query(Domain).filter_by(mail_host=mail_host).count() > 0 diff --git a/src/mailman/model/listmanager.py b/src/mailman/model/listmanager.py index d648a5bde..df1a31d04 100644 --- a/src/mailman/model/listmanager.py +++ b/src/mailman/model/listmanager.py @@ -52,9 +52,7 @@ class ListManager: raise InvalidEmailAddressError(fqdn_listname) list_id = '{0}.{1}'.format(listname, hostname) notify(ListCreatingEvent(fqdn_listname)) - mlist = store.find( - MailingList, - MailingList._list_id == list_id).one() + mlist = store.query(MailingList).filter_by(_list_id=list_id).first() if mlist: raise ListAlreadyExistsError(fqdn_listname) mlist = MailingList(fqdn_listname) @@ -68,40 +66,40 @@ class ListManager: """See `IListManager`.""" listname, at, hostname = fqdn_listname.partition('@') list_id = '{0}.{1}'.format(listname, hostname) - return store.find(MailingList, MailingList._list_id == list_id).one() + return store.query(MailingList).filter_by(_list_id=list_id).one() @dbconnection def get_by_list_id(self, store, list_id): """See `IListManager`.""" - return store.find(MailingList, MailingList._list_id == list_id).one() + return store.query(MailingList).filter_by(_list_id=list_id).one() @dbconnection def delete(self, store, mlist): """See `IListManager`.""" fqdn_listname = mlist.fqdn_listname notify(ListDeletingEvent(mlist)) - store.find(ContentFilter, ContentFilter.mailing_list == mlist).remove() - store.remove(mlist) + store.query(ContentFilter).filter_by(mailing_list=mlist).delete() + store.delete(mlist) notify(ListDeletedEvent(fqdn_listname)) @property @dbconnection def mailing_lists(self, store): """See `IListManager`.""" - for mlist in store.find(MailingList): + for mlist in store.query(MailingList).all(): yield mlist @dbconnection def __iter__(self, store): """See `IListManager`.""" - for mlist in store.find(MailingList): + for mlist in store.query(MailingList).all(): yield mlist @property @dbconnection def names(self, store): """See `IListManager`.""" - result_set = store.find(MailingList) + result_set = store.query(MailingList).all() for mail_host, list_name in result_set.values(MailingList.mail_host, MailingList.list_name): yield '{0}@{1}'.format(list_name, mail_host) @@ -110,7 +108,7 @@ class ListManager: @dbconnection def list_ids(self, store): """See `IListManager`.""" - result_set = store.find(MailingList) + result_set = store.query(MailingList).all() for list_id in result_set.values(MailingList._list_id): yield list_id @@ -118,7 +116,7 @@ class ListManager: @dbconnection def name_components(self, store): """See `IListManager`.""" - result_set = store.find(MailingList) + result_set = store.query(MailingList).all() for mail_host, list_name in result_set.values(MailingList.mail_host, MailingList.list_name): yield list_name, mail_host diff --git a/src/mailman/model/mailinglist.py b/src/mailman/model/mailinglist.py index ff757aa98..324d709d6 100644 --- a/src/mailman/model/mailinglist.py +++ b/src/mailman/model/mailinglist.py @@ -27,8 +27,9 @@ __all__ = [ import os -from sqlalchemy import ( Boolean, DateTime, Float, Integer, Unicode - PickleType, Interval) +from sqlalchemy import (Column, Boolean, DateTime, Float, Integer, Unicode, + PickleType, Interval, ForeignKey) +from sqlalchemy.orm import relationship from urlparse import urljoin from zope.component import getUtility from zope.event import notify @@ -66,7 +67,6 @@ from mailman.utilities.string import expand SPACE = ' ' UNDERSCORE = '_' - @implementer(IMailingList) class MailingList(Model): @@ -114,7 +114,7 @@ class MailingList(Model): autoresponse_owner_text = Column(Unicode) autorespond_postings = Column(Enum(enum=ResponseAction)) autoresponse_postings_text = Column(Unicode) - autorespond_requests = Column(Enum(Enum=ResponseAction)) + autorespond_requests = Column(Enum(enum=ResponseAction)) autoresponse_request_text = Column(Unicode) # Content filters. filter_action = Column(Enum(enum=FilterAction)) @@ -495,10 +495,13 @@ class MailingList(Model): class AcceptableAlias(Model): """See `IAcceptableAlias`.""" - id = Int(primary=True) + __tablename__ = 'acceptablealias' + + id = Column(Integer, primary_key=True) mailing_list_id = Column(Integer) - mailing_list = Reference(mailing_list_id, MailingList.id) + mailing_list = relationship('MailingList') + #mailing_list = Reference(mailing_list_id, MailingList.id) alias = Column(Unicode) @@ -547,10 +550,12 @@ class AcceptableAliasSet: class ListArchiver(Model): """See `IListArchiver`.""" - id = Int(primary=True) + __tablename__ = 'listarchiver' - mailing_list_id = Column(Integer) - mailing_list = Reference(mailing_list_id, MailingList.id) + id = Column(Integer, primary_key=True) + + mailing_list_id = Column(Integer, ForeignKey('mailinglist.id')) + mailing_list = relationship('MailingList') name = Column(Unicode) _is_enabled = Column(Boolean) diff --git a/src/mailman/model/member.py b/src/mailman/model/member.py index f7da6b012..739e35484 100644 --- a/src/mailman/model/member.py +++ b/src/mailman/model/member.py @@ -54,14 +54,14 @@ class Member(Model): __tablename__ = 'member' id = Column(Integer, primary_key=True) - _member_id = UUID() + _member_id = Column(UUID) role = Column(Enum(enum=MemberRole)) list_id = Column(Unicode) moderation_action = Column(Enum(enum=Action)) - address_id = Column(Integer, ForegignKey('address.id')) + address_id = Column(Integer, ForeignKey('address.id')) preferences_id = Column(Integer, ForeignKey('preferences.id')) - user_id = Column(Integer, ForiegnKey('user.id')) + user_id = Column(Integer, ForeignKey('user.id')) def __init__(self, role, list_id, subscriber): self._member_id = uid_factory.new_uid() diff --git a/src/mailman/model/message.py b/src/mailman/model/message.py index 64ee2c84a..9d7623d09 100644 --- a/src/mailman/model/message.py +++ b/src/mailman/model/message.py @@ -39,7 +39,7 @@ class Message(Model): __tablename__ = 'message' - id = Column(Integer, primary_key=True, default=AutoReload)) + id = Column(Integer, primary_key=True) message_id = Column(Unicode) message_id_hash = Column(Unicode) path = Column(Unicode) # TODO : was RawStr() diff --git a/src/mailman/model/messagestore.py b/src/mailman/model/messagestore.py index a4950e8c9..69860a6a1 100644 --- a/src/mailman/model/messagestore.py +++ b/src/mailman/model/messagestore.py @@ -128,14 +128,14 @@ class MessageStore: @property @dbconnection def messages(self, store): - for row in store.find(Message): + for row in store.query(Message).all(): yield self._get_message(row) @dbconnection def delete_message(self, store, message_id): - row = store.find(Message, message_id=message_id).one() + row = store.query(Message).filter_by(message_id=message_id).one() if row is None: raise LookupError(message_id) path = os.path.join(config.MESSAGES_DIR, row.path) os.remove(path) - store.remove(row) + store.delete(row) diff --git a/src/mailman/model/mime.py b/src/mailman/model/mime.py index 3fa051f10..3eac4f07b 100644 --- a/src/mailman/model/mime.py +++ b/src/mailman/model/mime.py @@ -39,11 +39,11 @@ from mailman.interfaces.mime import IContentFilter, FilterType class ContentFilter(Model): """A single filter criteria.""" - __tablename__ == 'contentfilter' + __tablename__ = 'contentfilter' id = Column(Integer, primary_key=True) - mailing_list_id = Column(Integer, ForiegnKey('mailinglist.id')) + mailing_list_id = Column(Integer, ForeignKey('mailinglist.id')) mailing_list = relationship('MailingList') filter_type = Column(Enum(enum=FilterType)) diff --git a/src/mailman/model/pending.py b/src/mailman/model/pending.py index cc203d270..0c41a4ac6 100644 --- a/src/mailman/model/pending.py +++ b/src/mailman/model/pending.py @@ -50,6 +50,8 @@ from mailman.utilities.modules import call_name class PendedKeyValue(Model): """A pended key/value pair, tied to a token.""" + __tablename__ = 'pendedkeyvalue' + def __init__(self, key, value): self.key = key self.value = value @@ -57,7 +59,7 @@ class PendedKeyValue(Model): id = Column(Integer, primary_key=True) key = Column(Unicode) value = Column(Unicode) - pended_id = Column(Integer) + pended_id = Column(Integer, ForeignKey('pended.id')) @@ -65,15 +67,17 @@ class PendedKeyValue(Model): class Pended(Model): """A pended event, tied to a token.""" + __tablename__ = 'pended' + def __init__(self, token, expiration_date): super(Pended, self).__init__() self.token = token self.expiration_date = expiration_date - id = Column(Integer. primary_key=True) + id = Column(Integer, primary_key=True) token = Column(Unicode) # TODO : was RawStr() expiration_date = Column(DateTime) - key_values = relationship('PendedKeyValues') + key_values = relationship('PendedKeyValue') @implementer(IPendable) diff --git a/src/mailman/model/preferences.py b/src/mailman/model/preferences.py index 73bb080a9..d74b17e30 100644 --- a/src/mailman/model/preferences.py +++ b/src/mailman/model/preferences.py @@ -41,7 +41,7 @@ from mailman.interfaces.preferences import IPreferences class Preferences(Model): """See `IPreferences`.""" - __tablename__ == 'preferences' + __tablename__ = 'preferences' id = Column(Integer, primary_key=True) acknowledge_posts = Column(Boolean) diff --git a/src/mailman/model/requests.py b/src/mailman/model/requests.py index 457341557..850ba6b3b 100644 --- a/src/mailman/model/requests.py +++ b/src/mailman/model/requests.py @@ -143,7 +143,7 @@ class ListRequests: class _Request(Model): """Table for mailing list hold requests.""" - __tablename__ == 'request' + __tablename__ = 'request' id = Column(Integer, primary_key=True)# TODO: ???, default=AutoReload) key = Column(Unicode) diff --git a/src/mailman/model/roster.py b/src/mailman/model/roster.py index 5a6a13269..f641c2846 100644 --- a/src/mailman/model/roster.py +++ b/src/mailman/model/roster.py @@ -37,7 +37,7 @@ __all__ = [ ] -from storm.expr import And, Or +#from storm.expr import And, Or from zope.interface import implementer from mailman.database.transaction import dbconnection diff --git a/src/mailman/model/user.py b/src/mailman/model/user.py index 16e87bbfb..88bf62085 100644 --- a/src/mailman/model/user.py +++ b/src/mailman/model/user.py @@ -25,7 +25,7 @@ __all__ = [ ] from sqlalchemy import Column, Unicode, Integer, DateTime, ForeignKey -from sqlalchemy import relationship, backref +from sqlalchemy.orm import relationship, backref from zope.event import notify from zope.interface import implementer @@ -59,11 +59,13 @@ class User(Model): _user_id = Column(UUID) _created_on = Column(DateTime) - addresses = relationship('Address', backref='user') + addresses = relationship('Address', + backref='user', + foreign_keys='[Address.user_id]') - _preferred_address_id = Column(Integer, ForeignKey='address.id') + _preferred_address_id = Column(Integer, ForeignKey('address.id')) _preferred_address = relationship('Address', - backred=backref('user', uselist=False)) + foreign_keys=[_preferred_address_id]) preferences_id = Column(Integer, ForeignKey('preferences.id')) preferences = relationship('Preferences', diff --git a/src/mailman/model/version.py b/src/mailman/model/version.py index 9824e54d4..8dc0d4e6c 100644 --- a/src/mailman/model/version.py +++ b/src/mailman/model/version.py @@ -32,7 +32,7 @@ from mailman.database.model import Model class Version(Model): - __tablename_ = 'version' + __tablename__ = 'version' id = Column(Integer, primary_key=True) component = Column(Unicode) -- cgit v1.2.3-70-g09d2 From f8212e1d9d32f29039b620d8805f1a53f579dd34 Mon Sep 17 00:00:00 2001 From: Abhilash Raj Date: Sat, 13 Sep 2014 22:48:48 +0530 Subject: fix all tests in mailman.model.tests --- src/mailman/app/subscriptions.py | 11 ++-- src/mailman/database/types.py | 6 +- src/mailman/model/address.py | 2 +- src/mailman/model/autorespond.py | 4 +- src/mailman/model/bans.py | 2 +- src/mailman/model/bounce.py | 2 +- src/mailman/model/domain.py | 3 +- src/mailman/model/listmanager.py | 2 +- src/mailman/model/mailinglist.py | 135 ++++++++++++++++++-------------------- src/mailman/model/member.py | 8 ++- src/mailman/model/message.py | 4 +- src/mailman/model/messagestore.py | 8 +-- src/mailman/model/pending.py | 25 +++---- src/mailman/model/requests.py | 21 +++--- src/mailman/model/roster.py | 11 ++-- src/mailman/model/user.py | 5 +- 16 files changed, 123 insertions(+), 126 deletions(-) (limited to 'src/mailman/model/message.py') diff --git a/src/mailman/app/subscriptions.py b/src/mailman/app/subscriptions.py index d24a9a545..a53d22e72 100644 --- a/src/mailman/app/subscriptions.py +++ b/src/mailman/app/subscriptions.py @@ -28,7 +28,7 @@ __all__ = [ from operator import attrgetter from passlib.utils import generate_password as generate -#from storm.expr import And, Or +from sqlalchemy import and_, or_ from uuid import UUID from zope.component import getUtility from zope.interface import implementer @@ -88,8 +88,7 @@ class SubscriptionService: @dbconnection def get_member(self, store, member_id): """See `ISubscriptionService`.""" - members = store.find( - Member, + members = store.query(Member).filter( Member._member_id == member_id) if members.count() == 0: return None @@ -117,7 +116,7 @@ class SubscriptionService: # This probably could be made more efficient. if address is None or user is None: return [] - query.append(Or(Member.address_id == address.id, + query.append(or_(Member.address_id == address.id, Member.user_id == user.id)) else: # subscriber is a user id. @@ -126,7 +125,7 @@ class SubscriptionService: if address.id is not None) if len(address_ids) == 0 or user is None: return [] - query.append(Or(Member.user_id == user.id, + query.append(or_(Member.user_id == user.id, Member.address_id.is_in(address_ids))) # Calculate the rest of the query expression, which will get And'd # with the Or clause above (if there is one). @@ -134,7 +133,7 @@ class SubscriptionService: query.append(Member.list_id == list_id) if role is not None: query.append(Member.role == role) - results = store.find(Member, And(*query)) + results = store.query(Member).filter(and_(*query)) return sorted(results, key=_membership_sort_key) def __iter__(self): diff --git a/src/mailman/database/types.py b/src/mailman/database/types.py index 045065591..81721781d 100644 --- a/src/mailman/database/types.py +++ b/src/mailman/database/types.py @@ -47,13 +47,17 @@ class Enum(TypeDecorator): TypeDecorator.__init__(self, *args, **kw) def process_bind_param(self, value, dialect): + if value is None: + return None if not isinstance(value, self.enum): raise ValueError("{} must be a value of the {} enum".format( - self.value, self.enum.__name__)) + value, self.enum.__name__)) return value.value def process_result_value(self, value, dialect): + if value is None: + return None return self.enum(value) diff --git a/src/mailman/model/address.py b/src/mailman/model/address.py index 59d54aab0..7203a31a5 100644 --- a/src/mailman/model/address.py +++ b/src/mailman/model/address.py @@ -56,7 +56,7 @@ class Address(Model): user_id = Column(Integer, ForeignKey('user.id')) preferences_id = Column(Integer, ForeignKey('preferences.id')) - prefereces = relationship('Preferences', + preferences = relationship('Preferences', backref=backref('Address', uselist=False)) def __init__(self, email, display_name): diff --git a/src/mailman/model/autorespond.py b/src/mailman/model/autorespond.py index 47f15cd54..17fe5fadc 100644 --- a/src/mailman/model/autorespond.py +++ b/src/mailman/model/autorespond.py @@ -75,7 +75,7 @@ class AutoResponseSet: @dbconnection def todays_count(self, store, address, response_type): """See `IAutoResponseSet`.""" - return store.find(AutoResponseRecord).filter_by( + return store.query(AutoResponseRecord).filter_by( address = address, mailing_list = self._mailing_list, response_type = response_type, @@ -91,7 +91,7 @@ class AutoResponseSet: @dbconnection def last_response(self, store, address, response_type): """See `IAutoResponseSet`.""" - results = store.find(AutoResponseRecord).filter_by( + results = store.query(AutoResponseRecord).filter_by( address = address, mailing_list = self._mailing_list, response_type = response_type diff --git a/src/mailman/model/bans.py b/src/mailman/model/bans.py index bf02f3127..d0f3b2519 100644 --- a/src/mailman/model/bans.py +++ b/src/mailman/model/bans.py @@ -103,7 +103,7 @@ class BanManager: if bans.count() > 0: return True # Now try specific mailing list bans, but with a pattern. - bans = store.query(Ban).filteR_by(list_id=list_id) + bans = store.query(Ban).filter_by(list_id=list_id) for ban in bans: if (ban.email.startswith('^') and re.match(ban.email, email, re.IGNORECASE) is not None): diff --git a/src/mailman/model/bounce.py b/src/mailman/model/bounce.py index 7340a4824..1165fee96 100644 --- a/src/mailman/model/bounce.py +++ b/src/mailman/model/bounce.py @@ -78,7 +78,7 @@ class BounceProcessor: @dbconnection def events(self, store): """See `IBounceProcessor`.""" - for event in store.find(BounceEvent): + for event in store.query(BounceEvent).all(): yield event @property diff --git a/src/mailman/model/domain.py b/src/mailman/model/domain.py index 860107b15..585eccf3d 100644 --- a/src/mailman/model/domain.py +++ b/src/mailman/model/domain.py @@ -94,8 +94,7 @@ class Domain(Model): @dbconnection def mailing_lists(self, store): """See `IDomain`.""" - mailing_lists = store.find( - MailingList, + mailing_lists = store.query(MailingList).filter( MailingList.mail_host == self.mail_host) for mlist in mailing_lists: yield mlist diff --git a/src/mailman/model/listmanager.py b/src/mailman/model/listmanager.py index a67f7b5e1..1279de6cc 100644 --- a/src/mailman/model/listmanager.py +++ b/src/mailman/model/listmanager.py @@ -116,7 +116,7 @@ class ListManager: @dbconnection def name_components(self, store): """See `IListManager`.""" - result_set = store.query(MailingList).all() + result_set = store.query(MailingList) for mail_host, list_name in result_set.values(MailingList.mail_host, MailingList.list_name): yield list_name, mail_host diff --git a/src/mailman/model/mailinglist.py b/src/mailman/model/mailinglist.py index b1997ef95..ed7ac5553 100644 --- a/src/mailman/model/mailinglist.py +++ b/src/mailman/model/mailinglist.py @@ -28,8 +28,8 @@ __all__ = [ import os from sqlalchemy import (Column, Boolean, DateTime, Float, Integer, Unicode, - PickleType, Interval, ForeignKey) -from sqlalchemy.orm import relationship + PickleType, Interval, ForeignKey, LargeBinary) +from sqlalchemy.orm import relationship, sessionmaker from urlparse import urljoin from zope.component import getUtility from zope.event import notify @@ -67,6 +67,8 @@ from mailman.utilities.string import expand SPACE = ' ' UNDERSCORE = '_' +Session = sessionmaker() + @implementer(IMailingList) class MailingList(Model): @@ -162,7 +164,7 @@ class MailingList(Model): member_moderation_notice = Column(Unicode) mime_is_default_digest = Column(Boolean) # FIXME: There should be no moderator_password - moderator_password = Column(Unicode) # TODO : was RawStr() + moderator_password = Column(LargeBinary) # TODO : was RawStr() newsgroup_moderation = Column(Enum(enum=NewsgroupModeration)) nntp_prefix_subject_too = Column(Boolean) nondigestable = Column(Boolean) @@ -327,26 +329,24 @@ class MailingList(Model): def send_one_last_digest_to(self, address, delivery_mode): """See `IMailingList`.""" digest = OneLastDigest(self, address, delivery_mode) - Store.of(self).add(digest) + Session.object_session(self).add(digest) @property def last_digest_recipients(self): """See `IMailingList`.""" - results = Store.of(self).find( - OneLastDigest, + results = Session.object_session(self).query(OneLastDigest).filter( OneLastDigest.mailing_list == self) recipients = [(digest.address, digest.delivery_mode) for digest in results] - results.remove() + results.delete() return recipients @property def filter_types(self): """See `IMailingList`.""" - results = Store.of(self).find( - ContentFilter, - And(ContentFilter.mailing_list == self, - ContentFilter.filter_type == FilterType.filter_mime)) + results = Session.object_session(self).query(ContentFilter).filter( + ContentFilter.mailing_list == self, + ContentFilter.filter_type == FilterType.filter_mime) for content_filter in results: yield content_filter.filter_pattern @@ -354,11 +354,11 @@ class MailingList(Model): def filter_types(self, sequence): """See `IMailingList`.""" # First, delete all existing MIME type filter patterns. - store = Store.of(self) + store = Session.object_session(self) results = store.query(ContentFilter).filter( ContentFilter.mailing_list == self, ContentFilter.filter_type == FilterType.filter_mime) - results.remove() + results.delete() # Now add all the new filter types. for mime_type in sequence: content_filter = ContentFilter( @@ -368,10 +368,9 @@ class MailingList(Model): @property def pass_types(self): """See `IMailingList`.""" - results = Store.of(self).find( - ContentFilter, - And(ContentFilter.mailing_list == self, - ContentFilter.filter_type == FilterType.pass_mime)) + results = Session.object_session(self).query(ContentFilter).filter( + ContentFilter.mailing_list == self, + ContentFilter.filter_type == FilterType.pass_mime) for content_filter in results: yield content_filter.filter_pattern @@ -379,12 +378,11 @@ class MailingList(Model): def pass_types(self, sequence): """See `IMailingList`.""" # First, delete all existing MIME type pass patterns. - store = Store.of(self) - results = store.find( - ContentFilter, - And(ContentFilter.mailing_list == self, - ContentFilter.filter_type == FilterType.pass_mime)) - results.remove() + store = Session.object_session(self) + results = store.query(ContentFilter).filter( + ContentFilter.mailing_list == self, + ContentFilter.filter_type == FilterType.pass_mime) + results.delete() # Now add all the new filter types. for mime_type in sequence: content_filter = ContentFilter( @@ -394,10 +392,9 @@ class MailingList(Model): @property def filter_extensions(self): """See `IMailingList`.""" - results = Store.of(self).find( - ContentFilter, - And(ContentFilter.mailing_list == self, - ContentFilter.filter_type == FilterType.filter_extension)) + results = Session.object_session(self).query(ContentFilter).filter( + ContentFilter.mailing_list == self, + ContentFilter.filter_type == FilterType.filter_extension) for content_filter in results: yield content_filter.filter_pattern @@ -405,12 +402,11 @@ class MailingList(Model): def filter_extensions(self, sequence): """See `IMailingList`.""" # First, delete all existing file extensions filter patterns. - store = Store.of(self) - results = store.find( - ContentFilter, - And(ContentFilter.mailing_list == self, - ContentFilter.filter_type == FilterType.filter_extension)) - results.remove() + store = Session.object_session(self) + results = store.query(ContentFilter).filter( + ContentFilter.mailing_list == self, + ContentFilter.filter_type == FilterType.filter_extension) + results.delete() # Now add all the new filter types. for mime_type in sequence: content_filter = ContentFilter( @@ -420,10 +416,9 @@ class MailingList(Model): @property def pass_extensions(self): """See `IMailingList`.""" - results = Store.of(self).find( - ContentFilter, - And(ContentFilter.mailing_list == self, - ContentFilter.filter_type == FilterType.pass_extension)) + results = Session.object_session(self).query(ContentFilter).filter( + ContentFilter.mailing_list == self, + ContentFilter.filter_type == FilterType.pass_extension) for content_filter in results: yield content_filter.pass_pattern @@ -431,12 +426,11 @@ class MailingList(Model): def pass_extensions(self, sequence): """See `IMailingList`.""" # First, delete all existing file extensions pass patterns. - store = Store.of(self) - results = store.find( - ContentFilter, - And(ContentFilter.mailing_list == self, - ContentFilter.filter_type == FilterType.pass_extension)) - results.remove() + store = Session.object_session(self) + results = store.query(ContentFilter).filter( + ContentFilter.mailing_list == self, + ContentFilter.filter_type == FilterType.pass_extension) + results.delete() # Now add all the new filter types. for mime_type in sequence: content_filter = ContentFilter( @@ -457,24 +451,22 @@ class MailingList(Model): def subscribe(self, subscriber, role=MemberRole.member): """See `IMailingList`.""" - store = Store.of(self) + store = Session.object_session(self) if IAddress.providedBy(subscriber): - member = store.find( - Member, + member = store.query(Member).filter( Member.role == role, Member.list_id == self._list_id, - Member._address == subscriber).one() + Member._address == subscriber).first() if member: raise AlreadySubscribedError( self.fqdn_listname, subscriber.email, role) elif IUser.providedBy(subscriber): if subscriber.preferred_address is None: raise MissingPreferredAddressError(subscriber) - member = store.find( - Member, + member = store.query(Member).filter( Member.role == role, Member.list_id == self._list_id, - Member._user == subscriber).one() + Member._user == subscriber).first() if member: raise AlreadySubscribedError( self.fqdn_listname, subscriber, role) @@ -518,27 +510,27 @@ class AcceptableAliasSet: def clear(self): """See `IAcceptableAliasSet`.""" - Store.of(self._mailing_list).find( - AcceptableAlias, - AcceptableAlias.mailing_list == self._mailing_list).remove() + Session.object_session(self._mailing_list).query( + AcceptableAlias).filter( + AcceptableAlias.mailing_list == self._mailing_list).delete() def add(self, alias): if not (alias.startswith('^') or '@' in alias): raise ValueError(alias) alias = AcceptableAlias(self._mailing_list, alias.lower()) - Store.of(self._mailing_list).add(alias) + Session.object_session(self._mailing_list).add(alias) def remove(self, alias): - Store.of(self._mailing_list).find( - AcceptableAlias, - And(AcceptableAlias.mailing_list == self._mailing_list, - AcceptableAlias.alias == alias.lower())).remove() + Session.object_session(self._mailing_list).query( + AcceptableAlias).filter( + AcceptableAlias.mailing_list == self._mailing_list, + AcceptableAlias.alias == alias.lower()).delete() @property def aliases(self): - aliases = Store.of(self._mailing_list).find( - AcceptableAlias, - AcceptableAlias.mailing_list == self._mailing_list) + aliases = Session.object_session(self._mailing_list).query( + AcceptableAlias).filter( + AcceptableAlias.mailing_list == self._mailing_list) for alias in aliases: yield alias.alias @@ -587,25 +579,24 @@ class ListArchiverSet: system_archivers[archiver.name] = archiver # Add any system enabled archivers which aren't already associated # with the mailing list. - store = Store.of(self._mailing_list) + store = Session.object_session(self._mailing_list) for archiver_name in system_archivers: - exists = store.find( - ListArchiver, - And(ListArchiver.mailing_list == mailing_list, - ListArchiver.name == archiver_name)).one() + exists = store.query(ListArchiver).filter( + ListArchiver.mailing_list == mailing_list, + ListArchiver.name == archiver_name).first() if exists is None: store.add(ListArchiver(mailing_list, archiver_name, system_archivers[archiver_name])) @property def archivers(self): - entries = Store.of(self._mailing_list).find( - ListArchiver, ListArchiver.mailing_list == self._mailing_list) + entries = Session.object_session(self._mailing_list).query( + ListArchiver).filter(ListArchiver.mailing_list == self._mailing_list) for entry in entries: yield entry def get(self, archiver_name): - return Store.of(self._mailing_list).find( - ListArchiver, - And(ListArchiver.mailing_list == self._mailing_list, - ListArchiver.name == archiver_name)).one() + return Session.object_session(self._mailing_list).query( + ListArchiver).filter( + ListArchiver.mailing_list == self._mailing_list, + ListArchiver.name == archiver_name).first() diff --git a/src/mailman/model/member.py b/src/mailman/model/member.py index 739e35484..f1007c311 100644 --- a/src/mailman/model/member.py +++ b/src/mailman/model/member.py @@ -25,6 +25,7 @@ __all__ = [ ] from sqlalchemy import Integer, Unicode, ForeignKey, Column +from sqlalchemy.orm import relationship from zope.component import getUtility from zope.event import notify from zope.interface import implementer @@ -60,8 +61,11 @@ class Member(Model): moderation_action = Column(Enum(enum=Action)) address_id = Column(Integer, ForeignKey('address.id')) + _address = relationship('Address') preferences_id = Column(Integer, ForeignKey('preferences.id')) + preferences = relationship('Preferences') user_id = Column(Integer, ForeignKey('user.id')) + _user = relationship('User') def __init__(self, role, list_id, subscriber): self._member_id = uid_factory.new_uid() @@ -196,5 +200,5 @@ class Member(Model): """See `IMember`.""" # Yes, this must get triggered before self is deleted. notify(UnsubscriptionEvent(self.mailing_list, self)) - store.remove(self.preferences) - store.remove(self) + store.delete(self.preferences) + store.delete(self) diff --git a/src/mailman/model/message.py b/src/mailman/model/message.py index 9d7623d09..b153d4909 100644 --- a/src/mailman/model/message.py +++ b/src/mailman/model/message.py @@ -24,7 +24,7 @@ __all__ = [ 'Message', ] -from sqlalchemy import Column, Integer, Unicode +from sqlalchemy import Column, Integer, Unicode, LargeBinary from zope.interface import implementer from mailman.database.model import Model @@ -42,7 +42,7 @@ class Message(Model): id = Column(Integer, primary_key=True) message_id = Column(Unicode) message_id_hash = Column(Unicode) - path = Column(Unicode) # TODO : was RawStr() + path = Column(LargeBinary) # TODO : was RawStr() # This is a Messge-ID field representation, not a database row id. @dbconnection diff --git a/src/mailman/model/messagestore.py b/src/mailman/model/messagestore.py index 69860a6a1..f9f224dd6 100644 --- a/src/mailman/model/messagestore.py +++ b/src/mailman/model/messagestore.py @@ -59,7 +59,7 @@ class MessageStore: # Calculate and insert the X-Message-ID-Hash. message_id = message_ids[0] # Complain if the Message-ID already exists in the storage. - existing = store.find(Message, Message.message_id == message_id).one() + existing = store.query(Message).filter(Message.message_id == message_id).first() if existing is not None: raise ValueError( 'Message ID already exists in message store: {0}'.format( @@ -107,7 +107,7 @@ class MessageStore: @dbconnection def get_message_by_id(self, store, message_id): - row = store.find(Message, message_id=message_id).one() + row = store.query(Message).filter_by(message_id=message_id).first() if row is None: return None return self._get_message(row) @@ -120,7 +120,7 @@ class MessageStore: # US-ASCII. if isinstance(message_id_hash, unicode): message_id_hash = message_id_hash.encode('ascii') - row = store.find(Message, message_id_hash=message_id_hash).one() + row = store.query(Message).filter_by(message_id_hash=message_id_hash).first() if row is None: return None return self._get_message(row) @@ -133,7 +133,7 @@ class MessageStore: @dbconnection def delete_message(self, store, message_id): - row = store.query(Message).filter_by(message_id=message_id).one() + row = store.query(Message).filter_by(message_id=message_id).first() if row is None: raise LookupError(message_id) path = os.path.join(config.MESSAGES_DIR, row.path) diff --git a/src/mailman/model/pending.py b/src/mailman/model/pending.py index 0c41a4ac6..30aae074c 100644 --- a/src/mailman/model/pending.py +++ b/src/mailman/model/pending.py @@ -31,7 +31,8 @@ import random import hashlib from lazr.config import as_timedelta -from sqlalchemy import Column, Integer, Unicode, ForeignKey, DateTime +from sqlalchemy import ( + Column, Integer, Unicode, ForeignKey, DateTime, LargeBinary) from sqlalchemy.orm import relationship from zope.interface import implementer from zope.interface.verify import verifyObject @@ -75,7 +76,7 @@ class Pended(Model): self.expiration_date = expiration_date id = Column(Integer, primary_key=True) - token = Column(Unicode) # TODO : was RawStr() + token = Column(LargeBinary) # TODO : was RawStr() expiration_date = Column(DateTime) key_values = relationship('PendedKeyValue') @@ -109,7 +110,7 @@ class Pendings: token = hashlib.sha1(repr(x)).hexdigest() # In practice, we'll never get a duplicate, but we'll be anal # about checking anyway. - if store.find(Pended, token=token).count() == 0: + if store.query(Pended).filter_by(token=token).count() == 0: break else: raise AssertionError('Could not find a valid pendings token') @@ -133,7 +134,7 @@ class Pendings: value = ('mailman.model.pending.unpack_list\1' + '\2'.join(value)) keyval = PendedKeyValue(key=key, value=value) - pending.key_values.add(keyval) + pending.key_values.append(keyval) store.add(pending) return token @@ -141,7 +142,7 @@ class Pendings: def confirm(self, store, token, expunge=True): # Token can come in as a unicode, but it's stored in the database as # bytes. They must be ascii. - pendings = store.find(Pended, token=str(token)) + pendings = store.query(Pended).filter_by(token=str(token)) if pendings.count() == 0: return None assert pendings.count() == 1, ( @@ -150,7 +151,7 @@ class Pendings: pendable = UnpendedPendable() # Find all PendedKeyValue entries that are associated with the pending # object's ID. Watch out for type conversions. - for keyvalue in store.find(PendedKeyValue, + for keyvalue in store.query(PendedKeyValue).filter( PendedKeyValue.pended_id == pending.id): if keyvalue.value is not None and '\1' in keyvalue.value: type_name, value = keyvalue.value.split('\1', 1) @@ -158,23 +159,23 @@ class Pendings: else: pendable[keyvalue.key] = keyvalue.value if expunge: - store.remove(keyvalue) + store.delete(keyvalue) if expunge: - store.remove(pending) + store.delete(pending) return pendable @dbconnection def evict(self, store): right_now = now() - for pending in store.find(Pended): + for pending in store.query(Pended).all(): if pending.expiration_date < right_now: # Find all PendedKeyValue entries that are associated with the # pending object's ID. - q = store.find(PendedKeyValue, + q = store.query(PendedKeyValue).filter( PendedKeyValue.pended_id == pending.id) for keyvalue in q: - store.remove(keyvalue) - store.remove(pending) + store.delete(keyvalue) + store.delete(pending) diff --git a/src/mailman/model/requests.py b/src/mailman/model/requests.py index 850ba6b3b..1b72f78f3 100644 --- a/src/mailman/model/requests.py +++ b/src/mailman/model/requests.py @@ -26,7 +26,7 @@ __all__ = [ from cPickle import dumps, loads from datetime import timedelta -from sqlalchemy import Column, Unicode, Integer, ForeignKey +from sqlalchemy import Column, Unicode, Integer, ForeignKey, LargeBinary from sqlalchemy.orm import relationship from zope.component import getUtility from zope.interface import implementer @@ -69,25 +69,23 @@ class ListRequests: @property @dbconnection def count(self, store): - return store.find(_Request, mailing_list=self.mailing_list).count() + return store.query(_Request).filter_by(mailing_list=self.mailing_list).count() @dbconnection def count_of(self, store, request_type): - return store.find( - _Request, + return store.query(_Request).filter_by( mailing_list=self.mailing_list, request_type=request_type).count() @property @dbconnection def held_requests(self, store): - results = store.find(_Request, mailing_list=self.mailing_list) + results = store.query(_Request).filter_by(mailing_list=self.mailing_list) for request in results: yield request @dbconnection def of_type(self, store, request_type): - results = store.find( - _Request, + results = store.query(_Request).filter_by( mailing_list=self.mailing_list, request_type=request_type) for request in results: yield request @@ -105,11 +103,12 @@ class ListRequests: data_hash = token request = _Request(key, request_type, self.mailing_list, data_hash) store.add(request) + store.flush() return request.id @dbconnection def get_request(self, store, request_id, request_type=None): - result = store.get(_Request, request_id) + result = store.query(_Request).get(request_id) if result is None: return None if request_type is not None and result.request_type != request_type: @@ -131,12 +130,12 @@ class ListRequests: @dbconnection def delete_request(self, store, request_id): - request = store.get(_Request, request_id) + request = store.query(_Request).get(request_id) if request is None: raise KeyError(request_id) # Throw away the pended data. getUtility(IPendings).confirm(request.data_hash) - store.remove(request) + store.delete(request) @@ -148,7 +147,7 @@ class _Request(Model): id = Column(Integer, primary_key=True)# TODO: ???, default=AutoReload) key = Column(Unicode) request_type = Column(Enum(enum=RequestType)) - data_hash = Column(Unicode) # TODO : was RawStr() + data_hash = Column(LargeBinary) mailing_list_id = Column(Integer, ForeignKey('mailinglist.id')) mailing_list = relationship('MailingList') diff --git a/src/mailman/model/roster.py b/src/mailman/model/roster.py index c8bfdc582..a9a396523 100644 --- a/src/mailman/model/roster.py +++ b/src/mailman/model/roster.py @@ -37,7 +37,6 @@ __all__ = [ ] -#from storm.expr import And, Or from sqlalchemy import and_, or_ from zope.interface import implementer @@ -203,9 +202,9 @@ class DeliveryMemberRoster(AbstractRoster): :return: A generator of members. :rtype: generator """ - results = store.query(Member).filter( - list_id == self._mlist.list_id, - role == MemberRole.member) + results = store.query(Member).filter_by( + list_id = self._mlist.list_id, + role = MemberRole.member) for member in results: if member.delivery_mode in delivery_modes: yield member @@ -263,9 +262,9 @@ class Memberships: def _query(self, store): results = store.query(Member).filter( or_(Member.user_id == self._user.id, - and_(Member.user_id == self._user.id, + and_(Address.user_id == self._user.id, Member.address_id == Address.id))) - return results.config(distinct=True) + return results.distinct() @property def member_count(self): diff --git a/src/mailman/model/user.py b/src/mailman/model/user.py index 0ba690805..12f4643f1 100644 --- a/src/mailman/model/user.py +++ b/src/mailman/model/user.py @@ -24,7 +24,8 @@ __all__ = [ 'User', ] -from sqlalchemy import Column, Unicode, Integer, DateTime, ForeignKey +from sqlalchemy import ( + Column, Unicode, Integer, DateTime, ForeignKey, LargeBinary) from sqlalchemy.orm import relationship, backref from zope.event import notify from zope.interface import implementer @@ -55,7 +56,7 @@ class User(Model): id = Column(Integer, primary_key=True) display_name = Column(Unicode) - _password = Column('password', Unicode) # TODO : was RawStr() + _password = Column('password', LargeBinary) # TODO : was RawStr() _user_id = Column(UUID) _created_on = Column(DateTime) -- cgit v1.2.3-70-g09d2 From c339f06cca6ddf1d28cde2614a94c2a0c905957a Mon Sep 17 00:00:00 2001 From: Abhilash Raj Date: Fri, 19 Sep 2014 22:41:56 +0530 Subject: * remove some unused code * add left out documentation * remov super().__init__() calls in models as it was useless now. * remove schema_migrate func in mailman/database/base.py --- src/mailman/database/base.py | 57 ++++++++++++++++++++----------------------- src/mailman/database/model.py | 17 ------------- src/mailman/model/address.py | 1 - src/mailman/model/message.py | 1 - src/mailman/model/pending.py | 1 - src/mailman/model/requests.py | 1 - src/mailman/model/uid.py | 1 - src/mailman/model/user.py | 1 - src/mailman/model/version.py | 1 - 9 files changed, 26 insertions(+), 55 deletions(-) (limited to 'src/mailman/model/message.py') diff --git a/src/mailman/database/base.py b/src/mailman/database/base.py index 5eec853d6..f379b3124 100644 --- a/src/mailman/database/base.py +++ b/src/mailman/database/base.py @@ -49,9 +49,12 @@ NL = '\n' class SABaseDatabase: """The database base class for use with SQLAlchemy. - Use this as a base class for your DB_Specific derived classes. + Use this as a base class for your DB-Specific derived classes. """ - TAG='' + # Tag used to distinguish the database being used. Override this in base + # classes. + + TAG = '' def __init__(self): self.url = None @@ -59,17 +62,18 @@ class SABaseDatabase: self.transaction = None def begin(self): + """See `IDatabase`.""" + # SA does this for us. pass def commit(self): + """See `IDatabase`.""" self.store.commit() def abort(self): + """See `IDatabase`.""" self.store.rollback() - def _prepare(self, url): - pass - def _database_exists(self): """Return True if the database exists and is initialized. @@ -97,11 +101,27 @@ class SABaseDatabase: database-specific post-removal cleanup. """ pass + def initialize(self, debug=None): + """See `IDatabase`""" + # Calculate the engine url url = expand(config.database.url, config.paths) log.debug('Database url: %s', url) + # XXX By design of SQLite, database file creation does not honor + # umask. See their ticket #1193: + # http://www.sqlite.org/cvstrac/tktview?tn=1193,31 + # + # This sucks for us because the mailman.db file /must/ be group + # writable, however even though we guarantee our umask is 002 here, it + # still gets created without the necessary g+w permission, due to + # SQLite's policy. This should only affect SQLite engines because its + # the only one that creates a little file on the local file system. + # This kludges around their bug by "touch"ing the database file before + # SQLite has any chance to create it, thus honoring the umask and + # ensuring the right permissions. We only try to do this for SQLite + # engines, and yes, we could have chmod'd the file after the fact, but + # half dozen and all... self.url = url - self._prepare(url) self.engine = create_engine(url) session = sessionmaker(bind=self.engine) self.store = session() @@ -133,31 +153,6 @@ class SABaseDatabase: if statement.strip() != '': store.execute(statement + ';') - def load_schema(self, store, version, filename, module_path): - """Load the schema from a file. - - This is a helper method for migration classes to call. - - :param store: The Storm store to load the schema into. - :type store: storm.locals.Store` - :param version: The schema version identifier of the form - YYYYMMDDHHMMSS. - :type version: string - :param filename: The file name containing the schema to load. Pass - `None` if there is no schema file to load. - :type filename: string - :param module_path: The fully qualified Python module path to the - migration module being loaded. This is used to record information - for use by the test suite. - :type module_path: string - """ - if filename is not None: - contents = resource_string('mailman.database.schema', filename) - self.load_sql(store, contents) - # Add a marker that indicates the migration version being applied. - store.add(Version(component='schema', version=version)) - - @staticmethod def _make_temporary(): diff --git a/src/mailman/database/model.py b/src/mailman/database/model.py index dedd7a34b..d86ebb80e 100644 --- a/src/mailman/database/model.py +++ b/src/mailman/database/model.py @@ -35,23 +35,6 @@ from mailman.config import config class ModelMeta(object): """Do more magic on table classes.""" - _class_registry = set() - - def __init__(self, name, bases, dict): - # Before we let the base class do it's thing, force an __tablename__ - # property to enforce our table naming convention. - self.__tablename__ = name.lower() - # super(ModelMeta, self).__init__(name, bases, dict) - # Register the model class so that it can be more easily cleared. - # This is required by the test framework so that the corresponding - # table can be reset between tests. - # - # The PRESERVE flag indicates whether the table should be reset or - # not. We have to handle the actual Model base class explicitly - # because it does not correspond to a table in the database. - if not getattr(self, 'PRESERVE', False) and name != 'Model': - ModelMeta._class_registry.add(self) - @staticmethod def _reset(db): meta = Model.metadata diff --git a/src/mailman/model/address.py b/src/mailman/model/address.py index fbe862829..7203a31a5 100644 --- a/src/mailman/model/address.py +++ b/src/mailman/model/address.py @@ -60,7 +60,6 @@ class Address(Model): backref=backref('Address', uselist=False)) def __init__(self, email, display_name): - super(Address, self).__init__() getUtility(IEmailValidator).validate(email) lower_case = email.lower() self.email = lower_case diff --git a/src/mailman/model/message.py b/src/mailman/model/message.py index b153d4909..39f33aa89 100644 --- a/src/mailman/model/message.py +++ b/src/mailman/model/message.py @@ -47,7 +47,6 @@ class Message(Model): @dbconnection def __init__(self, store, message_id, message_id_hash, path): - super(Message, self).__init__() self.message_id = message_id self.message_id_hash = message_id_hash self.path = path diff --git a/src/mailman/model/pending.py b/src/mailman/model/pending.py index 30aae074c..97d394721 100644 --- a/src/mailman/model/pending.py +++ b/src/mailman/model/pending.py @@ -71,7 +71,6 @@ class Pended(Model): __tablename__ = 'pended' def __init__(self, token, expiration_date): - super(Pended, self).__init__() self.token = token self.expiration_date = expiration_date diff --git a/src/mailman/model/requests.py b/src/mailman/model/requests.py index 1b72f78f3..88ad0e407 100644 --- a/src/mailman/model/requests.py +++ b/src/mailman/model/requests.py @@ -153,7 +153,6 @@ class _Request(Model): mailing_list = relationship('MailingList') def __init__(self, key, request_type, mailing_list, data_hash): - super(_Request, self).__init__() self.key = key self.request_type = request_type self.mailing_list = mailing_list diff --git a/src/mailman/model/uid.py b/src/mailman/model/uid.py index 6486089fa..77f1b59bb 100644 --- a/src/mailman/model/uid.py +++ b/src/mailman/model/uid.py @@ -54,7 +54,6 @@ class UID(Model): @dbconnection def __init__(self, store, uid): - super(UID, self).__init__() self.uid = uid store.add(self) diff --git a/src/mailman/model/user.py b/src/mailman/model/user.py index 37fb29e65..cd47a5dac 100644 --- a/src/mailman/model/user.py +++ b/src/mailman/model/user.py @@ -79,7 +79,6 @@ class User(Model): @dbconnection def __init__(self, store, display_name=None, preferences=None): - super(User, self).__init__() self._created_on = date_factory.now() user_id = uid_factory.new_uid() assert store.query(User).filter_by(_user_id=user_id).count() == 0, ( diff --git a/src/mailman/model/version.py b/src/mailman/model/version.py index 8dc0d4e6c..95cf03dac 100644 --- a/src/mailman/model/version.py +++ b/src/mailman/model/version.py @@ -43,6 +43,5 @@ class Version(Model): PRESERVE = True def __init__(self, component, version): - super(Version, self).__init__() self.component = component self.version = version -- cgit v1.2.3-70-g09d2 From 6b3114c4f0d458db25aa68dc44deeaca5b642ac4 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 22 Sep 2014 14:47:02 -0400 Subject: Clean up pass. --- src/mailman/app/subscriptions.py | 7 +- src/mailman/database/base.py | 25 +++-- src/mailman/database/factory.py | 1 + src/mailman/database/model.py | 28 +++-- src/mailman/database/sqlite.py | 4 +- src/mailman/database/types.py | 45 ++------ src/mailman/interfaces/database.py | 2 +- src/mailman/model/address.py | 9 +- src/mailman/model/autorespond.py | 19 ++-- src/mailman/model/bans.py | 4 +- src/mailman/model/bounce.py | 6 +- src/mailman/model/digests.py | 2 +- src/mailman/model/domain.py | 2 +- src/mailman/model/language.py | 2 +- src/mailman/model/mailinglist.py | 157 +++++++++++++++------------- src/mailman/model/member.py | 6 +- src/mailman/model/message.py | 3 +- src/mailman/model/messagestore.py | 16 +-- src/mailman/model/mime.py | 4 +- src/mailman/model/pending.py | 15 +-- src/mailman/model/preferences.py | 6 +- src/mailman/model/requests.py | 11 +- src/mailman/model/roster.py | 4 +- src/mailman/model/tests/test_listmanager.py | 7 +- src/mailman/model/uid.py | 3 +- src/mailman/model/user.py | 27 +++-- src/mailman/model/version.py | 3 +- src/mailman/utilities/importer.py | 15 ++- 28 files changed, 216 insertions(+), 217 deletions(-) (limited to 'src/mailman/model/message.py') diff --git a/src/mailman/app/subscriptions.py b/src/mailman/app/subscriptions.py index 303303e70..99c6ab2de 100644 --- a/src/mailman/app/subscriptions.py +++ b/src/mailman/app/subscriptions.py @@ -88,8 +88,7 @@ class SubscriptionService: @dbconnection def get_member(self, store, member_id): """See `ISubscriptionService`.""" - members = store.query(Member).filter( - Member._member_id == member_id) + members = store.query(Member).filter(Member._member_id == member_id) if members.count() == 0: return None else: @@ -117,7 +116,7 @@ class SubscriptionService: if address is None or user is None: return [] query.append(or_(Member.address_id == address.id, - Member.user_id == user.id)) + Member.user_id == user.id)) else: # subscriber is a user id. user = user_manager.get_user_by_id(subscriber) @@ -126,7 +125,7 @@ class SubscriptionService: if len(address_ids) == 0 or user is None: return [] query.append(or_(Member.user_id == user.id, - Member.address_id.in_(address_ids))) + Member.address_id.in_(address_ids))) # Calculate the rest of the query expression, which will get And'd # with the Or clause above (if there is one). if list_id is not None: diff --git a/src/mailman/database/base.py b/src/mailman/database/base.py index f379b3124..8c426f8cf 100644 --- a/src/mailman/database/base.py +++ b/src/mailman/database/base.py @@ -19,28 +19,22 @@ from __future__ import absolute_import, print_function, unicode_literals __metaclass__ = type __all__ = [ - 'StormBaseDatabase', + 'SABaseDatabase', ] -import os -import sys import logging -from lazr.config import as_boolean -from pkg_resources import resource_listdir, resource_string from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker -from sqlalchemy.orm.session import Session from zope.interface import implementer from mailman.config import config from mailman.interfaces.database import IDatabase -from mailman.model.version import Version from mailman.utilities.string import expand -log = logging.getLogger('mailman.config') +log = logging.getLogger('mailman.config') NL = '\n' @@ -53,17 +47,15 @@ class SABaseDatabase: """ # Tag used to distinguish the database being used. Override this in base # classes. - TAG = '' def __init__(self): self.url = None self.store = None - self.transaction = None def begin(self): """See `IDatabase`.""" - # SA does this for us. + # SQLAlchemy does this for us. pass def commit(self): @@ -102,9 +94,13 @@ class SABaseDatabase: """ pass + # XXX Abhilash removed teh _prepare() method. Is that because SA takes + # care of this for us? If so, then the comment below must be updated. + # For reference, the SQLite bug is marked "won't fix". + def initialize(self, debug=None): - """See `IDatabase`""" - # Calculate the engine url + """See `IDatabase`.""" + # Calculate the engine url. url = expand(config.database.url, config.paths) log.debug('Database url: %s', url) # XXX By design of SQLite, database file creation does not honor @@ -127,6 +123,9 @@ class SABaseDatabase: self.store = session() self.store.commit() + # XXX We should probably rename load_migrations() and perhaps get rid of + # load_sql(). The latter is never called any more. + def load_migrations(self, until=None): """Load schema migrations. diff --git a/src/mailman/database/factory.py b/src/mailman/database/factory.py index 64fcc242c..450672e5b 100644 --- a/src/mailman/database/factory.py +++ b/src/mailman/database/factory.py @@ -62,6 +62,7 @@ class DatabaseFactory: def _reset(self): """See `IDatabase`.""" + # Avoid a circular import at module level. from mailman.database.model import Model self.store.rollback() self._pre_reset(self.store) diff --git a/src/mailman/database/model.py b/src/mailman/database/model.py index d86ebb80e..f8a15162c 100644 --- a/src/mailman/database/model.py +++ b/src/mailman/database/model.py @@ -26,23 +26,31 @@ __all__ = [ import contextlib -from operator import attrgetter from sqlalchemy.ext.declarative import declarative_base from mailman.config import config -class ModelMeta(object): - """Do more magic on table classes.""" +class ModelMeta: + """The custom metaclass for all model base classes. + + This is used in the test suite to quickly reset the database after each + test. It works by iterating over all the tables, deleting each. The test + suite will then recreate the tables before each test. + """ @staticmethod def _reset(db): - meta = Model.metadata - engine = config.db.engine - with contextlib.closing(engine.connect()) as con: - trans = con.begin() - for table in reversed(meta.sorted_tables): - con.execute(table.delete()) - trans.commit() + with contextlib.closing(config.db.engine.connect()) as connection: + transaction = connection.begin() + try: + for table in reversed(Model.metadata.sorted_tables): + connection.execute(table.delete()) + except: + transaction.abort() + raise + else: + transaction.commit() + Model = declarative_base(cls=ModelMeta) diff --git a/src/mailman/database/sqlite.py b/src/mailman/database/sqlite.py index 0594d9091..b70e474cc 100644 --- a/src/mailman/database/sqlite.py +++ b/src/mailman/database/sqlite.py @@ -56,7 +56,7 @@ class SQLiteDatabase(SABaseDatabase): assert parts.scheme == 'sqlite', ( 'Database url mismatch (expected sqlite prefix): {0}'.format(url)) path = os.path.normpath(parts.path) - fd = os.open(path, os.O_WRONLY | os.O_NONBLOCK | os.O_CREAT, 0666) + fd = os.open(path, os.O_WRONLY | os.O_NONBLOCK | os.O_CREAT, 0o666) # Ignore errors if fd > 0: os.close(fd) @@ -72,7 +72,7 @@ def _cleanup(self, tempdir): def make_temporary(database): """Adapts by monkey patching an existing SQLite IDatabase.""" tempdir = tempfile.mkdtemp() - url = 'sqlite:///' + os.path.join(tempdir, 'mailman.db') + url = 'sqlite:///' + os.path.join(tempdir, 'mailman.db') with configuration('database', url=url): database.initialize() database._cleanup = types.MethodType( diff --git a/src/mailman/database/types.py b/src/mailman/database/types.py index a6f0b32ca..380ce37dc 100644 --- a/src/mailman/database/types.py +++ b/src/mailman/database/types.py @@ -29,30 +29,28 @@ __all__ = [ import uuid from sqlalchemy import Integer -from sqlalchemy.types import TypeDecorator, BINARY, CHAR from sqlalchemy.dialects import postgresql +from sqlalchemy.types import TypeDecorator, BINARY, CHAR class Enum(TypeDecorator): - """ - Stores an integer-based Enum as an integer in the database, and converts it - on-the-fly. - """ + """Handle Python 3.4 style enums. + Stores an integer-based Enum as an integer in the database, and + converts it on-the-fly. + """ impl = Integer - def __init__(self, *args, **kw): - self.enum = kw.pop("enum") - TypeDecorator.__init__(self, *args, **kw) + def __init__(self, enum, *args, **kw): + self.enum = enum + super(Enum, self).__init__(*args, **kw) def process_bind_param(self, value, dialect): if value is None: return None - return value.value - def process_result_value(self, value, dialect): if value is None: return None @@ -61,29 +59,12 @@ class Enum(TypeDecorator): class UUID(TypeDecorator): - """ - Stores a UUID in the database natively when it can and falls back to - a BINARY(16) or a CHAR(32) when it can't. - - :: - - from sqlalchemy_utils import UUIDType - import uuid - - class User(Base): - __tablename__ = 'user' + """Handle UUIds.""" - # Pass `binary=False` to fallback to CHAR instead of BINARY - id = sa.Column(UUIDType(binary=False), primary_key=True) - """ impl = BINARY(16) - python_type = uuid.UUID def __init__(self, binary=True, native=True): - """ - :param binary: Whether to use a BINARY(16) or CHAR(32) fallback. - """ self.binary = binary self.native = native @@ -91,7 +72,6 @@ class UUID(TypeDecorator): if dialect.name == 'postgresql' and self.native: # Use the native UUID type. return dialect.type_descriptor(postgresql.UUID()) - else: # Fallback to either a BINARY or a CHAR. kind = self.impl if self.binary else CHAR(32) @@ -102,29 +82,22 @@ class UUID(TypeDecorator): if value and not isinstance(value, uuid.UUID): try: value = uuid.UUID(value) - except (TypeError, ValueError): value = uuid.UUID(bytes=value) - return value def process_bind_param(self, value, dialect): if value is None: return value - if not isinstance(value, uuid.UUID): value = self._coerce(value) - if self.native and dialect.name == 'postgresql': return str(value) - return value.bytes if self.binary else value.hex def process_result_value(self, value, dialect): if value is None: return value - if self.native and dialect.name == 'postgresql': return uuid.UUID(value) - return uuid.UUID(bytes=value) if self.binary else uuid.UUID(value) diff --git a/src/mailman/interfaces/database.py b/src/mailman/interfaces/database.py index d8fde2b93..c2997ba6b 100644 --- a/src/mailman/interfaces/database.py +++ b/src/mailman/interfaces/database.py @@ -61,7 +61,7 @@ class IDatabase(Interface): """Abort the current transaction.""" store = Attribute( - """The underlying SQLAlchemy store on which you can do queries.""") + """The underlying database object on which you can do queries.""") diff --git a/src/mailman/model/address.py b/src/mailman/model/address.py index 7203a31a5..d078f28d5 100644 --- a/src/mailman/model/address.py +++ b/src/mailman/model/address.py @@ -26,8 +26,8 @@ __all__ = [ from email.utils import formataddr -from sqlalchemy import (Column, Integer, String, Unicode, - ForeignKey, DateTime) +from sqlalchemy import ( + Column, DateTime, ForeignKey, Integer, Unicode) from sqlalchemy.orm import relationship, backref from zope.component import getUtility from zope.event import notify @@ -56,10 +56,11 @@ class Address(Model): user_id = Column(Integer, ForeignKey('user.id')) preferences_id = Column(Integer, ForeignKey('preferences.id')) - preferences = relationship('Preferences', - backref=backref('Address', uselist=False)) + preferences = relationship( + 'Preferences', backref=backref('Address', uselist=False)) def __init__(self, email, display_name): + super(Address, self).__init__() getUtility(IEmailValidator).validate(email) lower_case = email.lower() self.email = lower_case diff --git a/src/mailman/model/autorespond.py b/src/mailman/model/autorespond.py index c3aff174a..c74434f7b 100644 --- a/src/mailman/model/autorespond.py +++ b/src/mailman/model/autorespond.py @@ -26,8 +26,7 @@ __all__ = [ ] -from sqlalchemy import (Column, Integer, String, Unicode, - ForeignKey, Date) +from sqlalchemy import Column, Date, ForeignKey, Integer from sqlalchemy import desc from sqlalchemy.orm import relationship from zope.interface import implementer @@ -55,7 +54,7 @@ class AutoResponseRecord(Model): mailing_list_id = Column(Integer, ForeignKey('mailinglist.id')) mailing_list = relationship('MailingList') - response_type = Column(Enum(enum=Response)) + response_type = Column(Enum(Response)) date_sent = Column(Date) def __init__(self, mailing_list, address, response_type): @@ -77,10 +76,10 @@ class AutoResponseSet: def todays_count(self, store, address, response_type): """See `IAutoResponseSet`.""" return store.query(AutoResponseRecord).filter_by( - address = address, - mailing_list = self._mailing_list, - response_type = response_type, - date_sent = today()).count() + address=address, + mailing_list=self._mailing_list, + response_type=response_type, + date_sent=today()).count() @dbconnection def response_sent(self, store, address, response_type): @@ -93,8 +92,8 @@ class AutoResponseSet: def last_response(self, store, address, response_type): """See `IAutoResponseSet`.""" results = store.query(AutoResponseRecord).filter_by( - address = address, - mailing_list = self._mailing_list, - response_type = response_type + address=address, + mailing_list=self._mailing_list, + response_type=response_type ).order_by(desc(AutoResponseRecord.date_sent)) return (None if results.count() == 0 else results.first()) diff --git a/src/mailman/model/bans.py b/src/mailman/model/bans.py index fbbecaebd..8678fc1e7 100644 --- a/src/mailman/model/bans.py +++ b/src/mailman/model/bans.py @@ -72,8 +72,8 @@ class BanManager: @dbconnection def unban(self, store, email): """See `IBanManager`.""" - ban = store.query(Ban).filter_by(email=email, - list_id=self._list_id).first() + ban = store.query(Ban).filter_by( + email=email, list_id=self._list_id).first() if ban is not None: store.delete(ban) diff --git a/src/mailman/model/bounce.py b/src/mailman/model/bounce.py index 1165fee96..cd658052d 100644 --- a/src/mailman/model/bounce.py +++ b/src/mailman/model/bounce.py @@ -27,7 +27,7 @@ __all__ = [ -from sqlalchemy import Column, Integer, Unicode, DateTime, Boolean +from sqlalchemy import Boolean, Column, DateTime, Integer, Unicode from zope.interface import implementer from mailman.database.model import Model @@ -50,7 +50,7 @@ class BounceEvent(Model): email = Column(Unicode) timestamp = Column(DateTime) message_id = Column(Unicode) - context = Column(Enum(enum=BounceContext)) + context = Column(Enum(BounceContext)) processed = Column(Boolean) def __init__(self, list_id, email, msg, context=None): @@ -85,5 +85,5 @@ class BounceProcessor: @dbconnection def unprocessed(self, store): """See `IBounceProcessor`.""" - for event in store.query(BounceEvent).filter_by(processed = False): + for event in store.query(BounceEvent).filter_by(processed=False): yield event diff --git a/src/mailman/model/digests.py b/src/mailman/model/digests.py index 1b7140824..7bfd512b6 100644 --- a/src/mailman/model/digests.py +++ b/src/mailman/model/digests.py @@ -50,7 +50,7 @@ class OneLastDigest(Model): address_id = Column(Integer, ForeignKey('address.id')) address = relationship('Address') - delivery_mode = Column(Enum(enum=DeliveryMode)) + delivery_mode = Column(Enum(DeliveryMode)) def __init__(self, mailing_list, address, delivery_mode): self.mailing_list = mailing_list diff --git a/src/mailman/model/domain.py b/src/mailman/model/domain.py index 585eccf3d..083e1cf51 100644 --- a/src/mailman/model/domain.py +++ b/src/mailman/model/domain.py @@ -26,8 +26,8 @@ __all__ = [ ] +from sqlalchemy import Column, Integer, Unicode from urlparse import urljoin, urlparse -from sqlalchemy import Column, Unicode, Integer from zope.event import notify from zope.interface import implementer diff --git a/src/mailman/model/language.py b/src/mailman/model/language.py index 7b611b6d8..15450c936 100644 --- a/src/mailman/model/language.py +++ b/src/mailman/model/language.py @@ -25,8 +25,8 @@ __all__ = [ ] +from sqlalchemy import Column, Integer, Unicode from zope.interface import implementer -from sqlalchemy import Column, Unicode, Integer from mailman.database import Model from mailman.interfaces import ILanguage diff --git a/src/mailman/model/mailinglist.py b/src/mailman/model/mailinglist.py index 385262f28..d00cf3d31 100644 --- a/src/mailman/model/mailinglist.py +++ b/src/mailman/model/mailinglist.py @@ -27,10 +27,11 @@ __all__ = [ import os -from sqlalchemy import (Column, Boolean, DateTime, Float, Integer, Unicode, - PickleType, Interval, ForeignKey, LargeBinary) -from sqlalchemy import event -from sqlalchemy.orm import relationship, sessionmaker +from sqlalchemy import ( + Boolean, Column, DateTime, Float, ForeignKey, Integer, Interval, + LargeBinary, PickleType, Unicode) +from sqlalchemy.event import listen +from sqlalchemy.orm import relationship from urlparse import urljoin from zope.component import getUtility from zope.event import notify @@ -38,6 +39,7 @@ from zope.interface import implementer from mailman.config import config from mailman.database.model import Model +from mailman.database.transaction import dbconnection from mailman.database.types import Enum from mailman.interfaces.action import Action, FilterAction from mailman.interfaces.address import IAddress @@ -68,7 +70,6 @@ from mailman.utilities.string import expand SPACE = ' ' UNDERSCORE = '_' -Session = sessionmaker() @implementer(IMailingList) @@ -100,9 +101,6 @@ class MailingList(Model): digest_last_sent_at = Column(DateTime) volume = Column(Integer) last_post_at = Column(DateTime) - # Implicit destination. - # acceptable_aliases_id = Column(Integer, ForeignKey('acceptablealias.id')) - # acceptable_alias = relationship('AcceptableAlias', backref='mailing_list') # Attributes which are directly modifiable via the web u/i. The more # complicated attributes are currently stored as pickles, though that # will change as the schema and implementation is developed. @@ -110,17 +108,17 @@ class MailingList(Model): admin_immed_notify = Column(Boolean) admin_notify_mchanges = Column(Boolean) administrivia = Column(Boolean) - archive_policy = Column(Enum(enum=ArchivePolicy)) + archive_policy = Column(Enum(ArchivePolicy)) # Automatic responses. autoresponse_grace_period = Column(Interval) - autorespond_owner = Column(Enum(enum=ResponseAction)) + autorespond_owner = Column(Enum(ResponseAction)) autoresponse_owner_text = Column(Unicode) - autorespond_postings = Column(Enum(enum=ResponseAction)) + autorespond_postings = Column(Enum(ResponseAction)) autoresponse_postings_text = Column(Unicode) - autorespond_requests = Column(Enum(enum=ResponseAction)) + autorespond_requests = Column(Enum(ResponseAction)) autoresponse_request_text = Column(Unicode) # Content filters. - filter_action = Column(Enum(enum=FilterAction)) + filter_action = Column(Enum(FilterAction)) filter_content = Column(Boolean) collapse_alternatives = Column(Boolean) convert_html_to_plaintext = Column(Boolean) @@ -132,18 +130,19 @@ class MailingList(Model): bounce_score_threshold = Column(Integer) # XXX bounce_you_are_disabled_warnings = Column(Integer) # XXX bounce_you_are_disabled_warnings_interval = Column(Interval) # XXX - forward_unrecognized_bounces_to = Column(Enum(enum=UnrecognizedBounceDisposition)) + forward_unrecognized_bounces_to = Column( + Enum(UnrecognizedBounceDisposition)) process_bounces = Column(Boolean) # Miscellaneous - default_member_action = Column(Enum(enum=Action)) - default_nonmember_action = Column(Enum(enum=Action)) + default_member_action = Column(Enum(Action)) + default_nonmember_action = Column(Enum(Action)) description = Column(Unicode) digest_footer_uri = Column(Unicode) digest_header_uri = Column(Unicode) digest_is_default = Column(Boolean) digest_send_periodic = Column(Boolean) digest_size_threshold = Column(Float) - digest_volume_frequency = Column(Enum(enum=DigestFrequency)) + digest_volume_frequency = Column(Enum(DigestFrequency)) digestable = Column(Boolean) discard_these_nonmembers = Column(PickleType) emergency = Column(Boolean) @@ -166,21 +165,21 @@ class MailingList(Model): mime_is_default_digest = Column(Boolean) # FIXME: There should be no moderator_password moderator_password = Column(LargeBinary) # TODO : was RawStr() - newsgroup_moderation = Column(Enum(enum=NewsgroupModeration)) + newsgroup_moderation = Column(Enum(NewsgroupModeration)) nntp_prefix_subject_too = Column(Boolean) nondigestable = Column(Boolean) nonmember_rejection_notice = Column(Unicode) obscure_addresses = Column(Boolean) owner_chain = Column(Unicode) owner_pipeline = Column(Unicode) - personalize = Column(Enum(enum=Personalization)) + personalize = Column(Enum(Personalization)) post_id = Column(Integer) posting_chain = Column(Unicode) posting_pipeline = Column(Unicode) _preferred_language = Column('preferred_language', Unicode) display_name = Column(Unicode) reject_these_nonmembers = Column(PickleType) - reply_goes_to_list = Column(Enum(enum=ReplyToMunging)) + reply_goes_to_list = Column(Enum(ReplyToMunging)) reply_to_address = Column(Unicode) require_explicit_destination = Column(Boolean) respond_to_post_requests = Column(Boolean) @@ -194,6 +193,7 @@ class MailingList(Model): welcome_message_uri = Column(Unicode) def __init__(self, fqdn_listname): + super(MailingList, self).__init__() listname, at, hostname = fqdn_listname.partition('@') assert hostname, 'Bad list name: {0}'.format(fqdn_listname) self.list_name = listname @@ -201,15 +201,15 @@ class MailingList(Model): self._list_id = '{0}.{1}'.format(listname, hostname) # For the pending database self.next_request_id = 1 - # We need to set up the rosters. Normally, this method will get - # called when the MailingList object is loaded from the database, but - # that's not the case when the constructor is called. So, set up the - # rosters explicitly. + # We need to set up the rosters. Normally, this method will get called + # when the MailingList object is loaded from the database, but when the + # constructor is called, SQLAlchemy's `load` event isn't triggered. + # Thus we need to set up the rosters explicitly. self._post_load() makedirs(self.data_path) - def _post_load(self, *args): + # This hooks up to SQLAlchemy's `load` event. self.owners = roster.OwnerRoster(self) self.moderators = roster.ModeratorRoster(self) self.administrators = roster.AdministratorRoster(self) @@ -221,7 +221,10 @@ class MailingList(Model): @classmethod def __declare_last__(cls): - event.listen(cls, 'load', cls._post_load) + # SQLAlchemy special directive hook called after mappings are assumed + # to be complete. Use this to connect the roster instance creation + # method with the SA `load` event. + listen(cls, 'load', cls._post_load) def __repr__(self): return ''.format( @@ -331,15 +334,17 @@ class MailingList(Model): except AttributeError: self._preferred_language = language - def send_one_last_digest_to(self, address, delivery_mode): + @dbconnection + def send_one_last_digest_to(self, store, address, delivery_mode): """See `IMailingList`.""" digest = OneLastDigest(self, address, delivery_mode) - Session.object_session(self).add(digest) + store.add(digest) @property - def last_digest_recipients(self): + @dbconnection + def last_digest_recipients(self, store): """See `IMailingList`.""" - results = Session.object_session(self).query(OneLastDigest).filter( + results = store.query(OneLastDigest).filter( OneLastDigest.mailing_list == self) recipients = [(digest.address, digest.delivery_mode) for digest in results] @@ -347,19 +352,20 @@ class MailingList(Model): return recipients @property - def filter_types(self): + @dbconnection + def filter_types(self, store): """See `IMailingList`.""" - results = Session.object_session(self).query(ContentFilter).filter( + results = store.query(ContentFilter).filter( ContentFilter.mailing_list == self, ContentFilter.filter_type == FilterType.filter_mime) for content_filter in results: yield content_filter.filter_pattern @filter_types.setter - def filter_types(self, sequence): + @dbconnection + def filter_types(self, store, sequence): """See `IMailingList`.""" # First, delete all existing MIME type filter patterns. - store = Session.object_session(self) results = store.query(ContentFilter).filter( ContentFilter.mailing_list == self, ContentFilter.filter_type == FilterType.filter_mime) @@ -371,19 +377,20 @@ class MailingList(Model): store.add(content_filter) @property - def pass_types(self): + @dbconnection + def pass_types(self, store): """See `IMailingList`.""" - results = Session.object_session(self).query(ContentFilter).filter( + results = store.query(ContentFilter).filter( ContentFilter.mailing_list == self, ContentFilter.filter_type == FilterType.pass_mime) for content_filter in results: yield content_filter.filter_pattern @pass_types.setter - def pass_types(self, sequence): + @dbconnection + def pass_types(self, store, sequence): """See `IMailingList`.""" # First, delete all existing MIME type pass patterns. - store = Session.object_session(self) results = store.query(ContentFilter).filter( ContentFilter.mailing_list == self, ContentFilter.filter_type == FilterType.pass_mime) @@ -395,19 +402,20 @@ class MailingList(Model): store.add(content_filter) @property - def filter_extensions(self): + @dbconnection + def filter_extensions(self, store): """See `IMailingList`.""" - results = Session.object_session(self).query(ContentFilter).filter( + results = store.query(ContentFilter).filter( ContentFilter.mailing_list == self, ContentFilter.filter_type == FilterType.filter_extension) for content_filter in results: yield content_filter.filter_pattern @filter_extensions.setter - def filter_extensions(self, sequence): + @dbconnection + def filter_extensions(self, store, sequence): """See `IMailingList`.""" # First, delete all existing file extensions filter patterns. - store = Session.object_session(self) results = store.query(ContentFilter).filter( ContentFilter.mailing_list == self, ContentFilter.filter_type == FilterType.filter_extension) @@ -419,19 +427,20 @@ class MailingList(Model): store.add(content_filter) @property - def pass_extensions(self): + @dbconnection + def pass_extensions(self, store): """See `IMailingList`.""" - results = Session.object_session(self).query(ContentFilter).filter( + results = store.query(ContentFilter).filter( ContentFilter.mailing_list == self, ContentFilter.filter_type == FilterType.pass_extension) for content_filter in results: yield content_filter.pass_pattern @pass_extensions.setter - def pass_extensions(self, sequence): + @dbconnection + def pass_extensions(self, store, sequence): """See `IMailingList`.""" # First, delete all existing file extensions pass patterns. - store = Session.object_session(self) results = store.query(ContentFilter).filter( ContentFilter.mailing_list == self, ContentFilter.filter_type == FilterType.pass_extension) @@ -454,9 +463,9 @@ class MailingList(Model): raise TypeError( 'Undefined MemberRole: {0}'.format(role)) - def subscribe(self, subscriber, role=MemberRole.member): + @dbconnection + def subscribe(self, store, subscriber, role=MemberRole.member): """See `IMailingList`.""" - store = Session.object_session(self) if IAddress.providedBy(subscriber): member = store.query(Member).filter( Member.role == role, @@ -512,29 +521,30 @@ class AcceptableAliasSet: def __init__(self, mailing_list): self._mailing_list = mailing_list - def clear(self): + @dbconnection + def clear(self, store): """See `IAcceptableAliasSet`.""" - Session.object_session(self._mailing_list).query( - AcceptableAlias).filter( - AcceptableAlias.mailing_list == self._mailing_list).delete() + store.query(AcceptableAlias).filter( + AcceptableAlias.mailing_list == self._mailing_list).delete() - def add(self, alias): + @dbconnection + def add(self, store, alias): if not (alias.startswith('^') or '@' in alias): raise ValueError(alias) alias = AcceptableAlias(self._mailing_list, alias.lower()) - Session.object_session(self._mailing_list).add(alias) + store.add(alias) - def remove(self, alias): - Session.object_session(self._mailing_list).query( - AcceptableAlias).filter( - AcceptableAlias.mailing_list == self._mailing_list, - AcceptableAlias.alias == alias.lower()).delete() + @dbconnection + def remove(self, store, alias): + store.query(AcceptableAlias).filter( + AcceptableAlias.mailing_list == self._mailing_list, + AcceptableAlias.alias == alias.lower()).delete() @property - def aliases(self): - aliases = Session.object_session(self._mailing_list).query( - AcceptableAlias).filter( - AcceptableAlias.mailing_list_id == self._mailing_list.id) + @dbconnection + def aliases(self, store): + aliases = store.query(AcceptableAlias).filter( + AcceptableAlias.mailing_list_id == self._mailing_list.id) for alias in aliases: yield alias.alias @@ -576,14 +586,14 @@ class ListArchiver(Model): @implementer(IListArchiverSet) class ListArchiverSet: - def __init__(self, mailing_list): + @dbconnection + def __init__(self, store, mailing_list): self._mailing_list = mailing_list system_archivers = {} for archiver in config.archivers: system_archivers[archiver.name] = archiver # Add any system enabled archivers which aren't already associated # with the mailing list. - store = Session.object_session(self._mailing_list) for archiver_name in system_archivers: exists = store.query(ListArchiver).filter( ListArchiver.mailing_list == mailing_list, @@ -593,14 +603,15 @@ class ListArchiverSet: system_archivers[archiver_name])) @property - def archivers(self): - entries = Session.object_session(self._mailing_list).query( - ListArchiver).filter(ListArchiver.mailing_list == self._mailing_list) + @dbconnection + def archivers(self, store): + entries = store.query(ListArchiver).filter( + ListArchiver.mailing_list == self._mailing_list) for entry in entries: yield entry - def get(self, archiver_name): - return Session.object_session(self._mailing_list).query( - ListArchiver).filter( - ListArchiver.mailing_list == self._mailing_list, - ListArchiver.name == archiver_name).first() + @dbconnection + def get(self, store, archiver_name): + return store.query(ListArchiver).filter( + ListArchiver.mailing_list == self._mailing_list, + ListArchiver.name == archiver_name).first() diff --git a/src/mailman/model/member.py b/src/mailman/model/member.py index f1007c311..9da9d5d0d 100644 --- a/src/mailman/model/member.py +++ b/src/mailman/model/member.py @@ -24,7 +24,7 @@ __all__ = [ 'Member', ] -from sqlalchemy import Integer, Unicode, ForeignKey, Column +from sqlalchemy import Column, ForeignKey, Integer, Unicode from sqlalchemy.orm import relationship from zope.component import getUtility from zope.event import notify @@ -56,9 +56,9 @@ class Member(Model): id = Column(Integer, primary_key=True) _member_id = Column(UUID) - role = Column(Enum(enum=MemberRole)) + role = Column(Enum(MemberRole)) list_id = Column(Unicode) - moderation_action = Column(Enum(enum=Action)) + moderation_action = Column(Enum(Action)) address_id = Column(Integer, ForeignKey('address.id')) _address = relationship('Address') diff --git a/src/mailman/model/message.py b/src/mailman/model/message.py index 39f33aa89..74a76ac30 100644 --- a/src/mailman/model/message.py +++ b/src/mailman/model/message.py @@ -24,7 +24,7 @@ __all__ = [ 'Message', ] -from sqlalchemy import Column, Integer, Unicode, LargeBinary +from sqlalchemy import Column, Integer, LargeBinary, Unicode from zope.interface import implementer from mailman.database.model import Model @@ -47,6 +47,7 @@ class Message(Model): @dbconnection def __init__(self, store, message_id, message_id_hash, path): + super(Message, self).__init__() self.message_id = message_id self.message_id_hash = message_id_hash self.path = path diff --git a/src/mailman/model/messagestore.py b/src/mailman/model/messagestore.py index f9f224dd6..0b8a0ac78 100644 --- a/src/mailman/model/messagestore.py +++ b/src/mailman/model/messagestore.py @@ -54,12 +54,13 @@ class MessageStore: def add(self, store, message): # Ensure that the message has the requisite headers. message_ids = message.get_all('message-id', []) - if len(message_ids) <> 1: + if len(message_ids) != 1: raise ValueError('Exactly one Message-ID header required') # Calculate and insert the X-Message-ID-Hash. message_id = message_ids[0] # Complain if the Message-ID already exists in the storage. - existing = store.query(Message).filter(Message.message_id == message_id).first() + existing = store.query(Message).filter( + Message.message_id == message_id).first() if existing is not None: raise ValueError( 'Message ID already exists in message store: {0}'.format( @@ -80,9 +81,9 @@ class MessageStore: # providing a unique serial number, but to get this information, we # have to use a straight insert instead of relying on Elixir to create # the object. - row = Message(message_id=message_id, - message_id_hash=hash32, - path=relpath) + Message(message_id=message_id, + message_id_hash=hash32, + path=relpath) # Now calculate the full file system path. path = os.path.join(config.MESSAGES_DIR, relpath) # Write the file to the path, but catch the appropriate exception in @@ -95,7 +96,7 @@ class MessageStore: pickle.dump(message, fp, -1) break except IOError as error: - if error.errno <> errno.ENOENT: + if error.errno != errno.ENOENT: raise makedirs(os.path.dirname(path)) return hash32 @@ -120,7 +121,8 @@ class MessageStore: # US-ASCII. if isinstance(message_id_hash, unicode): message_id_hash = message_id_hash.encode('ascii') - row = store.query(Message).filter_by(message_id_hash=message_id_hash).first() + row = store.query(Message).filter_by( + message_id_hash=message_id_hash).first() if row is None: return None return self._get_message(row) diff --git a/src/mailman/model/mime.py b/src/mailman/model/mime.py index 3eac4f07b..906af91ea 100644 --- a/src/mailman/model/mime.py +++ b/src/mailman/model/mime.py @@ -25,7 +25,7 @@ __all__ = [ ] -from sqlalchemy import Column, Integer, Unicode, ForeignKey +from sqlalchemy import Column, ForeignKey, Integer, Unicode from sqlalchemy.orm import relationship from zope.interface import implementer @@ -46,7 +46,7 @@ class ContentFilter(Model): mailing_list_id = Column(Integer, ForeignKey('mailinglist.id')) mailing_list = relationship('MailingList') - filter_type = Column(Enum(enum=FilterType)) + filter_type = Column(Enum(FilterType)) filter_pattern = Column(Unicode) def __init__(self, mailing_list, filter_pattern, filter_type): diff --git a/src/mailman/model/pending.py b/src/mailman/model/pending.py index 97d394721..a06a660b2 100644 --- a/src/mailman/model/pending.py +++ b/src/mailman/model/pending.py @@ -32,7 +32,7 @@ import hashlib from lazr.config import as_timedelta from sqlalchemy import ( - Column, Integer, Unicode, ForeignKey, DateTime, LargeBinary) + Column, DateTime, ForeignKey, Integer, LargeBinary, Unicode) from sqlalchemy.orm import relationship from zope.interface import implementer from zope.interface.verify import verifyObject @@ -71,6 +71,7 @@ class Pended(Model): __tablename__ = 'pended' def __init__(self, token, expiration_date): + super(Pended, self).__init__() self.token = token self.expiration_date = expiration_date @@ -79,6 +80,7 @@ class Pended(Model): expiration_date = Column(DateTime) key_values = relationship('PendedKeyValue') + @implementer(IPendable) class UnpendedPendable(dict): @@ -119,9 +121,9 @@ class Pendings: expiration_date=now() + lifetime) for key, value in pendable.items(): if isinstance(key, str): - key = unicode(key, 'utf-8') + key = key.encode('utf-8') if isinstance(value, str): - value = unicode(value, 'utf-8') + value = value.encode('utf-8') elif type(value) is int: value = '__builtin__.int\1%s' % value elif type(value) is float: @@ -150,8 +152,9 @@ class Pendings: pendable = UnpendedPendable() # Find all PendedKeyValue entries that are associated with the pending # object's ID. Watch out for type conversions. - for keyvalue in store.query(PendedKeyValue).filter( - PendedKeyValue.pended_id == pending.id): + entries = store.query(PendedKeyValue).filter( + PendedKeyValue.pended_id == pending.id) + for keyvalue in entries: if keyvalue.value is not None and '\1' in keyvalue.value: type_name, value = keyvalue.value.split('\1', 1) pendable[keyvalue.key] = call_name(type_name, value) @@ -171,7 +174,7 @@ class Pendings: # Find all PendedKeyValue entries that are associated with the # pending object's ID. q = store.query(PendedKeyValue).filter( - PendedKeyValue.pended_id == pending.id) + PendedKeyValue.pended_id == pending.id) for keyvalue in q: store.delete(keyvalue) store.delete(pending) diff --git a/src/mailman/model/preferences.py b/src/mailman/model/preferences.py index d74b17e30..1278f80b7 100644 --- a/src/mailman/model/preferences.py +++ b/src/mailman/model/preferences.py @@ -25,7 +25,7 @@ __all__ = [ ] -from sqlalchemy import Column, Integer, Unicode, Boolean +from sqlalchemy import Boolean, Column, Integer, Unicode from zope.component import getUtility from zope.interface import implementer @@ -49,8 +49,8 @@ class Preferences(Model): _preferred_language = Column('preferred_language', Unicode) receive_list_copy = Column(Boolean) receive_own_postings = Column(Boolean) - delivery_mode = Column(Enum(enum=DeliveryMode)) - delivery_status = Column(Enum(enum=DeliveryStatus)) + delivery_mode = Column(Enum(DeliveryMode)) + delivery_status = Column(Enum(DeliveryStatus)) def __repr__(self): return ''.format(id(self)) diff --git a/src/mailman/model/requests.py b/src/mailman/model/requests.py index 3d15ddea9..335e1e002 100644 --- a/src/mailman/model/requests.py +++ b/src/mailman/model/requests.py @@ -26,7 +26,7 @@ __all__ = [ from cPickle import dumps, loads from datetime import timedelta -from sqlalchemy import Column, Unicode, Integer, ForeignKey, LargeBinary +from sqlalchemy import Column, ForeignKey, Integer, LargeBinary, Unicode from sqlalchemy.orm import relationship from zope.component import getUtility from zope.interface import implementer @@ -69,7 +69,8 @@ class ListRequests: @property @dbconnection def count(self, store): - return store.query(_Request).filter_by(mailing_list=self.mailing_list).count() + return store.query(_Request).filter_by( + mailing_list=self.mailing_list).count() @dbconnection def count_of(self, store, request_type): @@ -79,7 +80,8 @@ class ListRequests: @property @dbconnection def held_requests(self, store): - results = store.query(_Request).filter_by(mailing_list=self.mailing_list) + results = store.query(_Request).filter_by( + mailing_list=self.mailing_list) for request in results: yield request @@ -148,13 +150,14 @@ class _Request(Model): id = Column(Integer, primary_key=True)# TODO: ???, default=AutoReload) key = Column(Unicode) - request_type = Column(Enum(enum=RequestType)) + request_type = Column(Enum(RequestType)) data_hash = Column(LargeBinary) mailing_list_id = Column(Integer, ForeignKey('mailinglist.id')) mailing_list = relationship('MailingList') def __init__(self, key, request_type, mailing_list, data_hash): + super(_Request, self).__init__() self.key = key self.request_type = request_type self.mailing_list = mailing_list diff --git a/src/mailman/model/roster.py b/src/mailman/model/roster.py index a9a396523..a6cbeb104 100644 --- a/src/mailman/model/roster.py +++ b/src/mailman/model/roster.py @@ -161,7 +161,7 @@ class AdministratorRoster(AbstractRoster): return store.query(Member).filter( Member.list_id == self._mlist.list_id, or_(Member.role == MemberRole.owner, - Member.role == MemberRole.moderator)) + Member.role == MemberRole.moderator)) @dbconnection def get_member(self, store, address): @@ -169,7 +169,7 @@ class AdministratorRoster(AbstractRoster): results = store.query(Member).filter( Member.list_id == self._mlist.list_id, or_(Member.role == MemberRole.moderator, - Member.role == MemberRole.owner), + Member.role == MemberRole.owner), Address.email == address, Member.address_id == Address.id) if results.count() == 0: diff --git a/src/mailman/model/tests/test_listmanager.py b/src/mailman/model/tests/test_listmanager.py index 3951e8250..b290138f3 100644 --- a/src/mailman/model/tests/test_listmanager.py +++ b/src/mailman/model/tests/test_listmanager.py @@ -29,11 +29,11 @@ __all__ = [ import unittest -from sqlalchemy.orm import sessionmaker from zope.component import getUtility from mailman.app.lifecycle import create_list from mailman.app.moderator import hold_message +from mailman.config import config from mailman.interfaces.listmanager import ( IListManager, ListCreatedEvent, ListCreatingEvent, ListDeletedEvent, ListDeletingEvent) @@ -148,9 +148,8 @@ Message-ID: for name in filter_names: setattr(self._ant, name, ['test-filter-1', 'test-filter-2']) getUtility(IListManager).delete(self._ant) - Session = sessionmaker() - store = Session.object_session(self._ant) - filters = store.query(ContentFilter).filter_by(mailing_list = self._ant) + filters = config.db.store.query(ContentFilter).filter_by( + mailing_list = self._ant) self.assertEqual(filters.count(), 0) diff --git a/src/mailman/model/uid.py b/src/mailman/model/uid.py index 77f1b59bb..29d8e7021 100644 --- a/src/mailman/model/uid.py +++ b/src/mailman/model/uid.py @@ -29,8 +29,8 @@ __all__ = [ from sqlalchemy import Column, Integer from mailman.database.model import Model -from mailman.database.types import UUID from mailman.database.transaction import dbconnection +from mailman.database.types import UUID @@ -54,6 +54,7 @@ class UID(Model): @dbconnection def __init__(self, store, uid): + super(UID, self).__init__() self.uid = uid store.add(self) diff --git a/src/mailman/model/user.py b/src/mailman/model/user.py index cd47a5dac..576015dbe 100644 --- a/src/mailman/model/user.py +++ b/src/mailman/model/user.py @@ -25,7 +25,7 @@ __all__ = [ ] from sqlalchemy import ( - Column, Unicode, Integer, DateTime, ForeignKey, LargeBinary) + Column, DateTime, ForeignKey, Integer, LargeBinary, Unicode) from sqlalchemy.orm import relationship, backref from zope.event import notify from zope.interface import implementer @@ -60,25 +60,24 @@ class User(Model): _user_id = Column(UUID) _created_on = Column(DateTime) - addresses = relationship('Address', - backref='user', - primaryjoin= - id==Address.user_id) + addresses = relationship( + 'Address', backref='user', + primaryjoin=(id==Address.user_id)) - _preferred_address_id = Column(Integer, ForeignKey('address.id', - use_alter=True, - name='_preferred_address')) - _preferred_address = relationship('Address', - primaryjoin= - _preferred_address_id==Address.id, - post_update=True) + _preferred_address_id = Column( + Integer, + ForeignKey('address.id', use_alter=True, name='_preferred_address')) + _preferred_address = relationship( + 'Address', primaryjoin=(_preferred_address_id==Address.id), + post_update=True) preferences_id = Column(Integer, ForeignKey('preferences.id')) - preferences = relationship('Preferences', - backref=backref('user', uselist=False)) + preferences = relationship( + 'Preferences', backref=backref('user', uselist=False)) @dbconnection def __init__(self, store, display_name=None, preferences=None): + super(User, self).__init__() self._created_on = date_factory.now() user_id = uid_factory.new_uid() assert store.query(User).filter_by(_user_id=user_id).count() == 0, ( diff --git a/src/mailman/model/version.py b/src/mailman/model/version.py index 95cf03dac..ecef6ed8a 100644 --- a/src/mailman/model/version.py +++ b/src/mailman/model/version.py @@ -24,9 +24,9 @@ __all__ = [ 'Version', ] -from sqlalchemy import Column, Unicode, Integer from mailman.database.model import Model +from sqlalchemy import Column, Integer, Unicode @@ -43,5 +43,6 @@ class Version(Model): PRESERVE = True def __init__(self, component, version): + super(Version, self).__init__() self.component = component self.version = version diff --git a/src/mailman/utilities/importer.py b/src/mailman/utilities/importer.py index 9856a8223..26b7261e3 100644 --- a/src/mailman/utilities/importer.py +++ b/src/mailman/utilities/importer.py @@ -186,7 +186,6 @@ NAME_MAPPINGS = dict( filter_mime_types='filter_types', generic_nonmember_action='default_nonmember_action', include_list_post_header='allow_list_posts', - last_post_time='last_post_at', member_moderation_action='default_member_action', mod_password='moderator_password', news_moderation='newsgroup_moderation', @@ -198,13 +197,13 @@ NAME_MAPPINGS = dict( send_welcome_msg='send_welcome_message', ) -# Datetime Fields that need a type conversion to python datetime -# object for SQLite database. -DATETIME_OBJECTS = [ +# These DateTime fields of the mailinglist table need a type conversion to +# Python datetime object for SQLite databases. +DATETIME_COLUMNS = [ 'created_at', 'digest_last_sent_at', 'last_post_time', -] + ] EXCLUDES = set(( 'digest_members', @@ -225,8 +224,8 @@ def import_config_pck(mlist, config_dict): # Some attributes must not be directly imported. if key in EXCLUDES: continue - # Created at must not be set, it needs a type conversion - if key in DATETIME_OBJECTS: + # These objects need explicit type conversions. + if key in DATETIME_COLUMNS: continue # Some attributes from Mailman 2 were renamed in Mailman 3. key = NAME_MAPPINGS.get(key, key) @@ -249,7 +248,7 @@ def import_config_pck(mlist, config_dict): except (TypeError, KeyError): print('Type conversion error for key "{}": {}'.format( key, value), file=sys.stderr) - for key in DATETIME_OBJECTS: + for key in DATETIME_COLUMNS: try: value = datetime.datetime.utcfromtimestamp(config_dict[key]) except KeyError: -- cgit v1.2.3-70-g09d2 From 95fc64b4894e5985bb8d0e5e944b2cda38c9a58c Mon Sep 17 00:00:00 2001 From: Abhilash Raj Date: Thu, 25 Sep 2014 18:36:24 +0530 Subject: Add support for postgresql * revert changes in message_id_has encoding by barry * Change message_id_hash column to LargeBinary (from previously mistaken one i.e.unicode) * add missing import in database/types.py * fix a bug in database/Model.py, transaction has no method abort(), instead it is rollback() --- src/mailman/database/model.py | 2 +- src/mailman/database/postgresql.py | 9 ++++----- src/mailman/database/types.py | 3 ++- src/mailman/model/docs/messagestore.rst | 5 ++--- src/mailman/model/message.py | 4 ++-- src/mailman/model/messagestore.py | 10 +++++++--- src/mailman/model/pending.py | 2 +- src/mailman/styles/base.py | 4 ++-- src/mailman/testing/testing.cfg | 6 +++--- src/mailman/utilities/importer.py | 9 +++++++++ 10 files changed, 33 insertions(+), 21 deletions(-) (limited to 'src/mailman/model/message.py') diff --git a/src/mailman/database/model.py b/src/mailman/database/model.py index 06705dfe9..b65d7d5eb 100644 --- a/src/mailman/database/model.py +++ b/src/mailman/database/model.py @@ -49,7 +49,7 @@ class ModelMeta: for table in reversed(Model.metadata.sorted_tables): connection.execute(table.delete()) except: - transaction.abort() + transaction.rollback() raise else: transaction.commit() diff --git a/src/mailman/database/postgresql.py b/src/mailman/database/postgresql.py index 59fff0865..ca1068302 100644 --- a/src/mailman/database/postgresql.py +++ b/src/mailman/database/postgresql.py @@ -40,15 +40,14 @@ class PostgreSQLDatabase(SABaseDatabase): restart from zero for new tests. """ super(PostgreSQLDatabase, self)._post_reset(store) - from mailman.database.model import ModelMeta - classes = sorted(ModelMeta._class_registry, - key=attrgetter('__storm_table__')) + from mailman.database.model import Model + tables = reversed(Model.metadata.sorted_tables) # Recipe adapted from # http://stackoverflow.com/questions/544791/ # django-postgresql-how-to-reset-primary-key - for model_class in classes: + for table in tables: store.execute("""\ SELECT setval('"{0}_id_seq"', coalesce(max("id"), 1), max("id") IS NOT null) FROM "{0}"; - """.format(model_class.__storm_table__)) + """.format(table)) diff --git a/src/mailman/database/types.py b/src/mailman/database/types.py index 641e065ba..eec6df6d5 100644 --- a/src/mailman/database/types.py +++ b/src/mailman/database/types.py @@ -30,6 +30,7 @@ import uuid from sqlalchemy import Integer from sqlalchemy.types import TypeDecorator, CHAR +from sqlalchemy.dialects import postgresql @@ -68,7 +69,7 @@ class UUID(TypeDecorator): def load_dialect_impl(self, dialect): if dialect.name == 'postgresql': - return dialect.type_descriptor(UUID()) + return dialect.type_descriptor(postgresql.UUID()) else: return dialect.type_descriptor(CHAR(32)) diff --git a/src/mailman/model/docs/messagestore.rst b/src/mailman/model/docs/messagestore.rst index f2f2ca9d2..bb853e575 100644 --- a/src/mailman/model/docs/messagestore.rst +++ b/src/mailman/model/docs/messagestore.rst @@ -28,9 +28,8 @@ header, you will get an exception. However, if the message has a ``Message-ID`` header, it can be stored. >>> msg['Message-ID'] = '<87myycy5eh.fsf@uwakimon.sk.tsukuba.ac.jp>' - >>> x_message_id_hash = message_store.add(msg) - >>> print(x_message_id_hash) - AGDWSNXXKCWEILKKNYTBOHRDQGOX3Y35 + >>> message_store.add(msg) + 'AGDWSNXXKCWEILKKNYTBOHRDQGOX3Y35' >>> print(msg.as_string()) Subject: An important message Message-ID: <87myycy5eh.fsf@uwakimon.sk.tsukuba.ac.jp> diff --git a/src/mailman/model/message.py b/src/mailman/model/message.py index 74a76ac30..c03d4bbd6 100644 --- a/src/mailman/model/message.py +++ b/src/mailman/model/message.py @@ -41,8 +41,8 @@ class Message(Model): id = Column(Integer, primary_key=True) message_id = Column(Unicode) - message_id_hash = Column(Unicode) - path = Column(LargeBinary) # TODO : was RawStr() + message_id_hash = Column(LargeBinary) + path = Column(LargeBinary) # This is a Messge-ID field representation, not a database row id. @dbconnection diff --git a/src/mailman/model/messagestore.py b/src/mailman/model/messagestore.py index 225d3d1ce..0b8a0ac78 100644 --- a/src/mailman/model/messagestore.py +++ b/src/mailman/model/messagestore.py @@ -66,7 +66,7 @@ class MessageStore: 'Message ID already exists in message store: {0}'.format( message_id)) shaobj = hashlib.sha1(message_id) - hash32 = base64.b32encode(shaobj.digest()).decode('ascii') + hash32 = base64.b32encode(shaobj.digest()) del message['X-Message-ID-Hash'] message['X-Message-ID-Hash'] = hash32 # Calculate the path on disk where we're going to store this message @@ -115,8 +115,12 @@ class MessageStore: @dbconnection def get_message_by_hash(self, store, message_id_hash): - if isinstance(message_id_hash, bytes): - message_id_hash = message_id_hash.decode('utf-8') + # It's possible the hash came from a message header, in which case it + # will be a Unicode. However when coming from source code, it may be + # an 8-string. Coerce to the latter if necessary; it must be + # US-ASCII. + if isinstance(message_id_hash, unicode): + message_id_hash = message_id_hash.encode('ascii') row = store.query(Message).filter_by( message_id_hash=message_id_hash).first() if row is None: diff --git a/src/mailman/model/pending.py b/src/mailman/model/pending.py index 68a8cd63e..691e94fd9 100644 --- a/src/mailman/model/pending.py +++ b/src/mailman/model/pending.py @@ -71,7 +71,7 @@ class Pended(Model): __tablename__ = 'pended' id = Column(Integer, primary_key=True) - token = Column(LargeBinary) # TODO : was RawStr() + token = Column(LargeBinary) expiration_date = Column(DateTime) key_values = relationship('PendedKeyValue') diff --git a/src/mailman/styles/base.py b/src/mailman/styles/base.py index d83b2e2a5..4f051c13c 100644 --- a/src/mailman/styles/base.py +++ b/src/mailman/styles/base.py @@ -67,9 +67,9 @@ class Identity: # Set this to Never if the list's preferred language uses us-ascii, # otherwise set it to As Needed. if mlist.preferred_language.charset == 'us-ascii': - mlist.encode_ascii_prefixes = 0 + mlist.encode_ascii_prefixes = False else: - mlist.encode_ascii_prefixes = 2 + mlist.encode_ascii_prefixes = True diff --git a/src/mailman/testing/testing.cfg b/src/mailman/testing/testing.cfg index fc76aa361..eb9de5513 100644 --- a/src/mailman/testing/testing.cfg +++ b/src/mailman/testing/testing.cfg @@ -18,9 +18,9 @@ # A testing configuration. # For testing against PostgreSQL. -# [database] -# class: mailman.database.postgresql.PostgreSQLDatabase -# url: postgres://barry:barry@localhost/mailman +[database] +class: mailman.database.postgresql.PostgreSQLDatabase +url: postgresql://maxking:maxking@localhost/mailman_test [mailman] site_owner: noreply@example.com diff --git a/src/mailman/utilities/importer.py b/src/mailman/utilities/importer.py index 26b7261e3..99531194f 100644 --- a/src/mailman/utilities/importer.py +++ b/src/mailman/utilities/importer.py @@ -128,6 +128,12 @@ def nonmember_action_mapping(value): }[value] +def int_to_bool(value): + if value: + return True + else: + return False + def check_language_code(code): if code is None: @@ -172,6 +178,9 @@ TYPES = dict( personalize=Personalization, preferred_language=check_language_code, reply_goes_to_list=ReplyToMunging, + allow_list_posts=int_to_bool, + include_rfc2369_headers=int_to_bool, + nntp_prefix_subject_too=int_to_bool, ) -- cgit v1.2.3-70-g09d2