aboutsummaryrefslogtreecommitdiff
path: root/dodai/config/db/__init__.py
blob: fa510acefdc00b7fd4724cad76ed52bbc065df02 (plain)
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
168
169
170
171
172
173
174
175
176
177
178
179
# Copyright (C) 2010  Leonard Thomas
#
# This file is part of Dodai.
#
# Dodai 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 3 of the License, or
# (at your option) any later version.
#
# Dodai 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 Dodai.  If not, see <http://www.gnu.org/licenses/>.

class ConfigDb(object):

    def __init__(self):
        self.connections = {}
        self._handlers = {}
        from dodai.config.db.sa import Sa
        self.register_handler('sa', Sa)

    def register_handler(self, name, obj):
        self._handlers[name] = [obj, None]

    def add_config(self, config_parser=None):
        if config_parser:
            if hasattr(config_parser, 'sections') and \
                    hasattr(config_parser, 'options'):
                config_obj = ConfigDbFile(config_parser)
                self._add_connections(config_obj)
            else:
                raise NotConfigParserObject()

    def _add_connections(self, config_obj):
        connections = config_obj()
        for name, obj in connections.items():
            self.connections[name] = obj

    def load(self, name):
        if name in self.connections:
            connection = self.connections[name]
            if connection.db_obj:
                return connection.db_obj
            else:
                handler = self._load_handler(connection.handler)
                db_obj = handler.load(connection)
                self.connections[name].db_obj = db_obj
                return db_obj

    def _load_handler(self, name):
        if name in self._handlers:
            handler = self._handlers[name]
            cls = handler[0]
            obj = handler[1]
            if not obj:
                obj = cls()
                self._handlers[name] = [cls, obj]
            return obj
        raise UnknownHandlerException(name)



class ConfigDbFile(object):

    OPTIONS_REQUIRED = [
        ['protocol', 'hostname', 'port', 'username', 'password','database'],
        ['protocol', 'filename']
    ]
    OPTIONS_EXTRA = ['protocol_extra', 'handler']
    DEFAULT_HANDLER = 'sa'

    def __init__(self, config_parser):
        self.parser = config_parser
        self._options = self._all_options()
        self.connections = {}

    def __call__(self):
        if not self.connections:
            for section in self.parser.sections():
                if self._is_valid(section):
                    obj = self._build_connection(section)
                    self.connections[obj.name] = obj
        return self.connections

    def _all_options(self):
        out = []
        for option_group in self.OPTIONS_REQUIRED:
            for option in option_group:
                if option not in out:
                    out.append(option)
        for option in self.OPTIONS_EXTRA:
            if option not in out:
                out.append(option)
        return out

    def _is_valid(self, section):
        for option_group in self.OPTIONS_REQUIRED:
            total = len(option_group)
            count = 0
            for option in option_group:
                if option in self.parser.options(section):
                    value = self.parser.get(section, option)
                    if value:
                        count += 1
            if count >= total:
                return True
        return False

    def _build_connection(self, section):
        obj = ConfigDbConnection()
        for option in self._options:
            obj.name = section
            if self.parser.has_option(section, option):
                value = self.parser.get(section, option)
                setattr(obj, option, value)
            if not hasattr(obj, 'handler') or not obj.handler:
                obj.handler = self.DEFAULT_HANDLER
        return obj


class BaseConfigDb(object):

    PROTOCOLS = ['postgresql', 'mysql', 'sqlite', 'mssql', 'oracle']

    def _clean(self, obj):
        obj.protocol = self._clean_protocol(obj.protocol)
        if hasattr(obj, 'port'):
            obj.port = self._clean_port(obj.port)

    def _clean_protocol(self, data):
        data = data.lower()
        if data in ('postgres', 'postgre'):
            data = 'postgresql'
        if data not in self.PROTOCOLS:
            raise InvalidProtocolException(data)
        else:
            return data

    def _clean_port(self, data):
        try:
            data = int(data)
        except ValueError:
            data = None
        except TypeError:
            data = None
        if data:
            if data <1 or data > 65535:
                raise InvalidPortException(data)
        return data


class ConfigDbConnection(object):

    def __init__(self):
        self.db_obj = None


class NotConfigParserObject(Exception):
    pass


class InvalidProtocolException(Exception):
    pass


class InvalidPortException(Exception):
    pass


class UnknownHandlerException(Exception):
    pass


class UnknownConnectionException(Exception):
    pass