Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

# Copyright (C) 2015 Chintalagiri Shashank 

# 

# This file is part of Tendril. 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU Affero General Public License as published by 

# the Free Software Foundation, either version 3 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 Affero General Public License for more details. 

# 

# You should have received a copy of the GNU Affero General Public License 

# along with this program.  If not, see <http://www.gnu.org/licenses/>. 

""" 

The Database Utils Module (:mod:`tendril.utils.db`) 

=================================================== 

 

This module provides utilities to deal with Tendril's Database. While the 

actual functionality is provided by the :mod:`sqlalchemy` package, the 

contents of this utility module simplify and specify the application code's 

interaction with :mod:`sqlalchemy` 

 

.. rubric:: Module Contents 

 

""" 

 

from sqlalchemy import create_engine 

from sqlalchemy.orm import sessionmaker 

from sqlalchemy.ext.declarative import declarative_base 

from sqlalchemy.ext.declarative import declared_attr 

from sqlalchemy import Column, Integer 

from sqlalchemy_utils import ArrowType 

 

from contextlib import contextmanager 

import functools 

import arrow 

 

from tendril.utils.config import DB_URI 

 

from tendril.utils import log 

logger = log.get_logger(__name__, log.DEFAULT) 

log.logging.getLogger('sqlalchemy.engine').setLevel(log.WARNING) 

 

 

def init_db_engine(): 

    """ 

    Initializes the database engine and binds it to the Database URI 

    defined by the :mod:`tendril.utils.config` module. 

 

    This function is called within the module and an engine is readily 

    available in the module variable :data:`tendril.utils.db.engine`. 

    Application code should not have to create a new engine for normal 

    use cases. 

    """ 

    return create_engine(DB_URI) 

 

#: The :class:`sqlalchemy.Engine` object 

engine = init_db_engine() 

 

#: The :class:`sqlalchemy.sessionmaker` bound to the database engine 

Session = sessionmaker(expire_on_commit=False) 

Session.configure(bind=engine) 

 

 

@contextmanager 

def get_session(): 

    """ 

    Application executable code will typically only have to interact with this 

    ``contextmanager`` or the :func:`with_db` decorator. It should use this to 

    create a database session, perform its tasks, whatever they may be, within 

    this context, and then exit the context. 

 

    If any Exception is thrown, the session is rolled back completely. If no 

    Exception is thrown or Exceptions are handled by the application code 

    within the context, the session is committed when the context exits. 

 

    .. seealso:: :func:`with_db` 

 

    """ 

    session = Session() 

    try: 

        yield session 

        session.commit() 

    except: 

        session.rollback() 

        raise 

    finally: 

        session.close() 

 

 

def with_db(func): 

    """ 

    Application executable code will typically only have to interact with this 

    function or the :func:`get_session` ``contextmanager``. The 

    :func:`with_db` decorator is intended to decorate functions which interact 

    primarily with the db. 

 

    Such a function would accept only keyword arguments, one of which is 

    ``session``, which can be a database session (created by 

    :func:`get_session`) provided by the caller. If ``session`` is ``None``, 

    this decorator creates a new session and calls the decorated function 

    using it. 

 

    Any function which returns objects that still need to be bound to a db 

    session should be called with a valid session, if you intend to do 

    anything with the returned objects. They will still execute without 

    exception if no session is provided, but the returned value may not be 

    useful. 

 

    .. seealso:: :func:`get_session` 

 

    """ 

    @functools.wraps(func) 

    def inner(session=None, **kwargs): 

        if session is None: 

            with get_session() as s: 

                return func(session=s, **kwargs) 

        else: 

            return func(session=session, **kwargs) 

    return inner 

 

 

#: The :mod:`sqlalchemy` declarative base for all Models in Tendril 

DeclBase = declarative_base() 

 

 

class BaseMixin(object): 

    """ 

    This Mixin can / should be used (by inheriting from) by all Model classes 

    defined by application code. It defines the :attr:`__tablename__` 

    attribute of the Model class to the name of the class and creates a 

    Primary Key Column named id in the table for the Model. 

    """ 

    @declared_attr 

    def __tablename__(self): 

        return self.__name__ 

 

    # __table_args__ = {'mysql_engine': 'InnoDB'} 

    # __mapper_args__= {'always_refresh': True} 

 

    id = Column(Integer, primary_key=True) 

 

 

class TimestampMixin(object): 

    """ 

    This Mixin can be used by any Models which require a timestamp to be 

    created. It adds a column named ``created_at``, which defaults to the 

    time at which the object is instantiated. 

    """ 

    created_at = Column(ArrowType, default=arrow.utcnow()) 

 

 

def commit_metadata(): 

    """ 

    This function commits all metadata to the table. This function should be 

    run after importing **all** the Model classes, and it will create the 

    tables in the database. 

    """ 

    from tendril.entityhub.db import model  # noqa 

    from tendril.inventory.db import model  # noqa 

    from tendril.dox.db import model        # noqa 

    from tendril.testing.db import model    # noqa 

 

    DeclBase.metadata.create_all(engine)