aboutsummaryrefslogtreecommitdiff
path: root/dodai/config/databases/__init__.py
blob: da317e838533035b8feb407f68711d64d3eb4c60 (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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# 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 ConfigDatabases(object):
    """An object that is used for creating database connection objects

    """
    def __init__(self):
        self.sections = {}
        self._handlers = {}

    def add(self, sections):
        """Adds a dictionary of section (objects) to this object that could
        be used for creating database connection objects

        """
        self._build_default_handler()
        for name, section in sections.items():
            self.sections[name] = DatabaseConnectionValidator(
                    name, section, self._handlers)

    def load(self, section_name):
        """Returns a database connection object of the given section_name.
        Throws Exceptions for any type of configuration errors or missing
        configuration data

        """
        if section_name in self.sections:
            return self.sections[section_name].load()
        else:
            raise UnknownDatabaseConnectionException(section_name)

    def _build_default_handler(self):
        # Creates the default sqlalchemy handler
        if 'sa' not in self._handlers:
            from dodai.config.databases.sa import Sa
            from sqlalchemy.orm import sessionmaker
            from sqlalchemy import create_engine
            from dodai.db import Db
            sa = Sa(create_engine, sessionmaker, Db)
            self._handlers['sa'] = sa

    def add_handler(self, name, handler):
        """Adds the given handler and name to this objects handlers

        """
        self._handlers[name] = obj


class DatabaseConnectionValidator(object):
    """Database validation object that is used to validate a section
    object which is basically a python object that can have the following
    properties:

              protocol: The database engine (postgresql, mysql, sqlite,
                        oracle, mssql etc..)

              hostname: The hostname or ip address of the database server

                  port: The port that should be used to connect to the
                        database server should be a number between 1
                        and 65535

              username: The username used to connect to the database server

              password: The password used to connect to the database server

              database: The database to connect to once connected to the
                        server

                schema: The schema that will be used.  This option does
                        not do anything but will exist in the db object
                        for use

              filename: The file path to the database file (sqlite)

        protocol_extra: Used to tell the handler which python db engine
                        to use.  For example one might want to tell
                        the sqlalchemy handler to use the psycopg2
                        python object.

               handler: The handler used to build the orm object. Dodai
                        only works with sqlalchemy so the default 'sa'
                        is used.
    Not all of the above options are required.

    """
    OPTIONS_REQUIRED = {
    'server':['protocol', 'hostname', 'port', 'username', 'password',
              'database'],
    'file'  :['protocol', 'filename']
    }
    OPTIONS_EXTRA = ['protocol_extra', 'handler', 'schema']
    SERVER_PROTOCOLS = ['postgresql', 'mysql', 'sqlite', 'mssql', 'oracle']
    FILE_PROTOCOLS = ['sqlite']
    DEFAULT_HANDLER = 'sa'

    def __init__(self, name, section, handlers):
        self.section = section
        self.name = name
        self.database_type = self._database_type()
        self._handlers = handlers
        self.obj = None

    def load(self):
        if not self.obj:
            self._validate()
            handler = self._get_handler()
            self.obj = handler(self.name, self.section)
        return self.obj

    def _get_handler(self):
        if hasattr(self.section, 'handler'):
            name = self.section.handler.lower()
            if handler in self._handlers.keys():
                return self._handlers[name]
        return self._handlers[self.DEFAULT_HANDLER]

    def _validate(self):
        if self.database_type == 'server':
            self._validate_protocol()
            self._validate_port()
            self._validate_option('username')
            self._validate_option('password')
            self._validate_option('database')
        elif self.database_type == 'file':
            self._validate_protocol()
            self._validate_option('filename')
        else:
            raise DatabaseConnectionException(self.name, self.OPTIONS_REQUIRED)

    def _validate_option(self, name):
        if not self.section[name]:
            raise DatabaseEmptyOptionException(self.name, name)
        return True

    def _validate_hostname(self):
        if not self.section.hostname:
            raise DatabaseHostnameException(self.name, self.section.hostname)
        return True

    def _validate_port(self):
        try:
            port = int(self.section.port)
        except ValueError:
            pass
        else:
            if port >=1 and port <=65535:
                return True
        raise DatabasePortException(self.name, self.section.port)

    def _validate_protocol(self):
        if self.database_type == 'server':
            if self.section.protocol not in self.SERVER_PROTOCOLS:
                raise DatabaseProtocolException(self.name,
                        self.section.protocol, self.database_type,
                        self.SERVER_PROTOCOLS)
            else:
                return True
        elif self.database_type == 'file':
            if self.section.protocol not in self.FILE_PROTOCOLS:
                raise DatabaseProtocolException(self.name,
                        self.section.protocol, self.database_type,
                        self.FILE_PROTOCOLS)
            else:
                return True
        else:
            return False

    def _database_type(self):
        keys = self.section.___options___.keys()
        for type_, pool in self.OPTIONS_REQUIRED.items():
            out = True
            for key in keys:
                if key not in pool:
                    out = False
            if out:
                return type_
        return False


class DatabaseEmptyOptionException(Exception):
    """Exception raised for an emption option in the config

    Attributes:
        section_name:       The section of the config file that contains
                            the invalid protocol
        option_name:        The name of the empty option

    """
    MESSAGE = "In the '{section_name}' section, the '{option_name}' "\
              "was not set.  Please set this option."

    def __init__(self, section_name, option_name):
        self.section_name = section_name
        self.option_name = option_name
        self.msg = self._build_message()

    def _build_message(self):
        return self.MESSAGE.format(section_name=self.section_name,
                                   option_name=self.option_name)


class DatabasePortException(Exception):
    """Exception raised for invalid database port connection

    Attributes:
        section_name:       The section of the config file that contains
                            the invalid protocol
        section_port:       The port value that was listed in the
                            config file

    """
    MESSAGE = "In the '{section_name}' section, the port of "\
              "'{section_port}' is invalid.  The port must be a "\
              "number between 1 and 65535"

    def __init__(self, section_name, section_port):
        self.section_name = section_name
        self.section_port = section_port
        self.msg = self._build_message()

    def _build_message(self):
        return self.MESSAGE.format(section_name=self.section_name,
                                   section_port=self.section_port)


class DatabaseHostnameException(Exception):
    """Exception raised for invalid database hostname

    Attributes:
        section_name:       The section of the config file that contains
                            the invalid protocol
        section_hostname:   The hostname value that was listed in the
                            config file

    """
    MESSAGE = "In the '{section_name}' section, the hostname of "\
              "'{section_hostname}' is invalid.  Please use a valid "\
              "hostname."

    MSG_NON = "In the '{section_name}' section, the hostname was "\
              "not set.  Please set the hostname."

    def __init__(self, section_name, section_hostname):
        self.section_name = section_name
        self.section_hostname = section_hostname
        self.msg = self._build_message()

    def _build_message(self):
        if self.section_hostname:
            return self.MESSAGE.format(section_name=self.section_name,
                                       section_hostname=self.section_hostname)
        else:
            return self.MSG_NON.format(section_name=self.section_name)


class DatabaseProtocolException(Exception):
    """Exception raised for invalid database connection protocols

    Attributes:
        section_name:       The section of the config file that contains
                            the invalid protocol
        section_protocol:   The protocol value that was listed in the
                            config file
        database_type:      Usually 'server' or 'file'
        protocols:          List of valid protocols

    """
    MESSAGE = "In the '{section_name}' section, the protocol of "\
              "'{section_protocol}' is invalid.  The valid protocols "\
              "for a '{database_type}' connection are: {protocols}"

    def __init__(self, section_name, section_protocol, database_type,
                 protocols):
        self.section_name = section_name
        self.section_protocol = section_protocol
        self.database_type = database_type
        self.protocols = protocols
        self.msg = self._build_message()

    def _build_message(self):
        protocols = ', '.join(self.protocols)
        return self.MESSAGE.format(section_name=self.section_name,
                                   section_protocol=self.section_protocol,
                                   database_type=self.database_type,
                                   protocols=protocols)


class DatabaseConnectionException(Exception):
    """Exception raised for missing database connection parameters

    Attributes:
        section_name:       The section of the config file that contains
                            the invalid connection information
        options_required:   A dictionary containing the database_type
                            as the key and a list of required options
                            as the value

    """
    MESSAGE =  "The '{section_name}' section does not contain all of the "\
               "correct information needed to make a database connection."
    MSG_TYPE = "To make a '{database_type}' connection please make sure "\
               "To have all of the following options: {options}."
    MSG_END =  "Please remember that the option names are case sensitive."

    def __init__(self, section_name, options_required):
        self.section_name = section_name
        self.options_required = options_required
        self.msg = self._build_message()

    def _build_message(self):
        out = []
        out.append(self.MESSAGE.format(section_name=self.section_name))
        for database_type, options in self.options_required.items():
            options = list_to_english(options)
            out.append(self.MSG_TYPE.format(database_type=database_type,
                                            options=options))
        out.append(self.MSG_END)
        return '  '.join(out)


class UnknownDatabaseConnectionException(Exception):
    """Exception raised for missing database connection parameters

    Attributes:
        section:  The requested section of the config file that can not
                  be found.

    """
    MESSAGE = "Unable to find the '{section}' section to create a "\
              "database connection."

    def __init__(self, section):
        self.section = section
        self.msg = self._build_message()

    def _build_message(self):
        return self.MESSAGE.format(section=self.section)


def list_to_english(data):
    """Takes the input list and creates a string with each option
    encased in single quotes and seperated by a comma with exception
    of the last option which is prefixed with the word 'and'

    """
    if data:
        if len(data) > 1:
            out = []
            last = "'{0}'".format(data.pop())
            for row in data:
                out.append("'{0}'".format(row))
            out = ', '.join(out)
            return "{0} and {1}".format(out, last)
        else:
            return "'{0}'".format(data.pop())