aboutsummaryrefslogtreecommitdiff
path: root/dodai/config/db/sa.py
blob: 06adf9c0c2a7dbff830f26eea5ffa18a06337751 (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
# 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/>.

from dodai.config.db import BaseConfigDb
from dodai.db import Db

class Sa(BaseConfigDb):


    def load(self, obj):
        from sqlalchemy.orm import sessionmaker
        self._clean(obj)
        db = Db()
        db.engine = self._build_engine(obj)
        Session = sessionmaker(bind=db.engine)
        db.session = Session()
        db.name = obj.name
        db.protocol = obj.protocol
        if hasattr(obj, 'filename') and obj.filename:
            db.filename = obj.filename
        else:
            db.hostname = obj.hostname
            if hasattr(obj, 'port') and obj.port:
                db.port = obj.port
            db.database = obj.database
        return db

    def _build_connection_string(self, obj):
        out = []
        out.append('{db.protocol}')
        if hasattr(obj, 'protocol_extra') and obj.protocol_extra:
            out.append('+{db.protocol_extra}')
        out.append('://')
        if hasattr(obj, 'filename') and obj.filename:
            out.append('{db.filename}')
        else:
            out.append('{db.username}:{db.password}@')
            out.append('{db.hostname}')
            if hasattr(obj, 'port') and obj.port:
                out.append(':{db.port}')
            out.append('/{db.database}')
        out = ''.join(out)
        out = out.format(db=obj)
        return out

    def _build_engine(self, obj):
        from sqlalchemy import create_engine
        connection_string = self._build_connection_string(obj)
        db_obj = create_engine(connection_string)
        return db_obj