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
|
# 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 Sa(object):
def __init__(self, create_engine, session_maker, result_object):
self._create_engine = create_engine
self._session_maker = session_maker
self._result_object = result_object
def __call__(self, name, obj):
db = self._result_object()
db.name = name
db.protocol = obj.protocol
if hasattr(obj, 'protocol_extra') and obj.protocol_extra:
db.protocol_extra = obj.protocol_extra
if hasattr(obj, 'filename') and obj.filename:
db.filename = obj.filename
if hasattr(obj, 'port') and obj.port:
db.port = int(obj.port)
if hasattr(obj, 'database') and obj.database:
db.database = obj.database
if hasattr(obj, 'schema') and obj.schema:
db.schema = obj.schema
if hasattr(obj, 'username') and obj.username:
db.username = obj.username
if hasattr(obj, 'hostname') and obj.hostname:
db.hostname = obj.hostname
db.engine = self._build_engine(obj)
db.session = self._build_session(db.engine)
return db
def _build_session(self, engine):
session = self._session_maker(bind=engine)
return session()
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):
connection_string = self._build_connection_string(obj)
db_obj = self._create_engine(connection_string)
return db_obj
|