view backend/sqlalchemy/SqlAlchemyBackend.py @ 144:74217db92993

updating feeds on the couchdb backend works now
author Dirk Olmes <dirk@xanthippe.ping.de>
date Wed, 24 Aug 2011 11:54:06 +0200
parents 32a173cb081c
children 71c5dc02ff87
line wrap: on
line source


from Preferences import Preferences
from datetime import datetime, timedelta
from sqlalchemy.sql import and_
import Database
import FeedList
import FeedUpdater
import Mapping
import logging
import util

class SqlAlchemyBackend(object):
    '''
    Backend that uses sqlalchemy for persistence
    '''

    def __init__(self):
        self._initLogging()
        self.session = Database.createSession()
        self.prefs = Preferences(self.session)
        self.updater = None

    def _initLogging(self):
        logging.getLogger("sqlalchemy.orm").setLevel(logging.WARN)

        sqlalchemyLogLevel = logging.ERROR
        if util.databaseLoggingEnabled():
            sqlalchemyLogLevel = logging.INFO
        logging.getLogger("sqlalchemy").setLevel(sqlalchemyLogLevel)

    def preferences(self):
        return self.prefs

    def getFeeds(self):
        return FeedList.getFeeds(self.session)

    def toggleRead(self, feedEntry):
        feedEntry.toggleRead()
        self.session.commit()

    def markAllEntriesRead(self, feed):
        feed.markAllEntriesRead()
        self.session.commit()

    def createFeed(self, url):
        try:
            FeedUpdater.createNewFeed(url, self.session)
            self.session.commit()
        except AttributeError as ae:
            self.session.rollback()
            raise ae

    def updateFeed(self, feed, changes):
        feed.takeChangesFrom(changes)
        feed.incrementNextUpdateDate()
        self.session.commit()

    def deleteFeed(self, feed):
        self.session.delete(feed)
        self.session.commit()

    def markFeedEntriesAsRead(self, entries):
        for entry in entries:
            entry.markRead()
        self.session.commit()

    def updateAllFeeds(self):
        FeedUpdater.updateAllFeeds(self.session)
        self.session.commit()

    def expireFeedEntries(self):
        logger = logging.getLogger("feedupdater")
        expireDate = self._calculateExpireDate()
        logger.info("expiring entries older than " + str(expireDate))
        feedEntry = Mapping.feedEntryTable
        deleteStatement = feedEntry.delete().where(
            and_(feedEntry.c.create_timestamp < expireDate, feedEntry.c.read == 1)
        )
        deleteStatement.execute()
        self.session.commit()

    def _calculateExpireDate(self):
        now = datetime.now()
        daysToKeepFeedEntries = self.prefs.daysToKeepFeedEntries()
        delta = timedelta(days=daysToKeepFeedEntries)
        return now - delta

    def dispose(self):
        # save all uncommitted state, just in case
        self.session.commit()
        self.session.close()