# -*- coding: utf-8 -*- # # Copyright (C) 2007, 2008, 2009 by Jan Dittberner. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, # USA. # # Version: $Id$ """This module defines the BackendEntityHandler class.""" import logging from sqlalchemy.orm import create_session, mapper, relation from gnuviechadmin.backend.tables import dbsetup class BackendEntityHandler(object): """This class is a handler for BackendEntity instances.""" def __init__(self, entityclass, toclass, config, verbose = False): """Initialize the handler with a specific entity class, transfer object class and verbosity flag.""" self.logger = logging.getLogger("%s.%s" % ( self.__class__.__module__, self.__class__.__name__)) dbsetup(config) self.entityclass = entityclass self.toclass = toclass self.config = config self.verbose = verbose def create(self, **kwargs): """Create a new entity of the managed type with the fields set to the values in kwargs.""" self.logger.debug("create with params %s", str(kwargs)) delegate = self.toclass(self.config, **kwargs) entity = self.entityclass(self.config, delegate, self.verbose) sess = create_session() try: sess.begin() sess.add(delegate) sess.flush() sess.refresh(delegate) entity.create_hook(sess) sess.commit() except: sess.rollback() self.logger.exception("Exception in create.") raise return entity def fetchall(self, **kwargs): """Fetches all entities of the managed entity type.""" self.logger.debug("fetchall with params %s", str(kwargs)) session = create_session() query = session.query(self.toclass) if kwargs: allentities = query.filter_by(**kwargs).all() else: allentities = query.all() return [self.entityclass(self.config, entity, self.verbose) \ for entity in allentities] def delete(self, pkvalue): """Deletes the entity of the managed entity type that has the specified primary key value.""" self.logger.debug("delete with primary key %s", str(pkvalue)) sess = create_session() try: sess.begin() tobj = sess.query(self.toclass).get(pkvalue) if tobj: entity = self.entityclass(self.config, tobj, self.verbose) self.logger.info("delete %s", str(entity)) if self.verbose: print "delete %s" % (str(entity)) entity.delete_hook(sess) sess.delete(tobj) sess.commit() except Exception: sess.rollback() self.logger.exception("Exception in delete.") raise