apsUserDbApiBase.py 3.63 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python

from dm.common.exceptions.dmException import DmException
from dm.common.exceptions.internalError import InternalError
from dm.common.utility.loggingManager import LoggingManager
from dm.aps_user_db.impl.apsUserDbManager import ApsUserDbManager

class ApsUserDbApiBase:
    """ APS User DB API base class. """
    def __init__(self):
        self.logger = LoggingManager.getInstance().getLogger(self.__class__.__name__)
        self.dbManager = ApsUserDbManager.getInstance()

    # Decorator for all DB queries
    @classmethod
    def executeQuery(cls, func):
        def query(*args, **kwargs):
            try:
                dbManager = ApsUserDbManager.getInstance()
                session = dbManager.openSession()
                kwargs['session'] = session
                try:
                    return func(*args, **kwargs)
                except DmException, ex:
                    raise
                except Exception, ex:
                    cls.getLogger().exception('%s' % ex)
                    raise DmException(exception=ex)
            finally:
                dbManager.closeSession(session)
        return query

    # Decorator for all DB transactions
    @classmethod
    def executeTransaction(cls, func):
        def transaction(*args, **kwargs):
            try:
                dbManager = ApsUserDbManager.getInstance()
                session = dbManager.openSession()
                kwargs['session'] = session
                try:
                    result = func(*args, **kwargs)
                    session.commit()
                    return result
                except DmException, ex:
                    session.rollback()
                    raise
                except Exception, ex:
                    session.rollback()
                    cls.getLogger().exception('%s' % ex)
                    raise DmException(exception=ex)
            finally:
                dbManager.closeSession(session)
        return transaction

    @classmethod
    def getLogger(cls):
        logger = LoggingManager.getInstance().getLogger(cls.__name__)
        return logger

    @classmethod
    def executeConnectionQuery(cls, query):
        connection = None
        try:
            connection = ApsUserDbManager.getInstance().acquireConnection()
            try:
                return connection.execute(query)
            except DmException, ex:
                raise
            except Exception, ex:
                cls.getLogger().exception('%s' % ex)
                raise
        finally:
            ApsUserDbManager.getInstance().releaseConnection(connection)


    def loadRelation(self, dbObject, relationName):
        if not relationName in dir(dbObject):
            raise InternalError('Relation %s not valid for class %s'
                % (relationName, dbObject.__class__.__name__))
        o = None
        exec 'o = dbObject.%s' % (relationName)
        return o

    def loadRelations(self, dbObject, optionDict):
        for k in optionDict.keys():
            # The optionDict contains key-value pairs of relation name
            # and a boolean to indicate whether to load that relation
            if not optionDict[k]:
                continue

            try:
                self.loadRelation(dbObject, k)
            except InternalError, ex:
                self.logger.error(ex)

    def toDmObjectList(self, dbEntityList):
        dmObjectList = []
        for dbEntity in dbEntityList:
            dmObjectList.append(dbEntity.getDmObject())
        return dmObjectList


#######################################################################
# Testing.
if __name__ == '__main__':
    api = ApsUserDbApiBase()