# 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 . class Sa(object): """Callable object that will wire up sqlalchemy engine and session objects Attributes: create_engine: The sqlalchemy create_engine object session_maker: The sqlalchemy session_maker object result_object: The object that will be populated with all the connection information along with the sqlalchemy objects """ 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, section, name): db = self._result_object() db.name = name db.protocol = section['protocol'] if section.has_key('protocol_extra') and section['protocol_extra']: db.protocol_extra = section['protocol_extra'] if section.has_key('filename') and section['filename']: db.filename = section['filename'] if section.has_key('port') and section['port']: db.port = int(section['port']) if section.has_key('database') and section['database']: db.database = section['database'] if section.has_key('schema') and section['schema']: db.schema = section['schema'] if section.has_key('username') and section['username']: db.username = section['username'] if section.has_key('hostname') and section['hostname']: db.hostname = section['hostname'] db.engine = self._build_engine(section) 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, section): out = [] out.append('{section[protocol]}') if section.has_key('protocol_extra') and section['protocol_extra']: out.append('+{section[protocol_extra]}') out.append('://') if section.has_key('filename') and section['filename']: out.append('/{section[filename]}') else: out.append('{section[username]}:{section[password]}@') out.append('{section[hostname]}') if section.has_key('port') and section['port']: out.append(':{section[port]}') out.append('/{section[database]}') out = ''.join(out) out = out.format(section=section) return out def _build_engine(self, section): connection_string = self._build_connection_string(section) db_obj = self._create_engine(connection_string) return db_obj