"""SQLAlchemy descriptions of databases, providing an object oriented interface

This file also contains database connection strings, which helps centralize
them in a single location.
"""
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

import BioSQL as biosql

__all__ = ['get_session']

_global_mappings = []

_config = dict(
 testing = dict(
  biosql =
  "mysql://user:pass@localhost:3306/biosql_results_test",
  ),
 production = dict(
  biosql = "mysql://user:pass@server:3306/wormbase_lite",
  ),
 to_include = ['biosql'])

def get_session(db_type):
    """Retrieve an ORM connection to an SQLAlchemy database.
    """
    Session = sessionmaker(twophase = True)
    # only load the mappings a single time for each instance
    if db_type not in _global_mappings:
        for add_name in _config['to_include']:
            dsn = _config[db_type][add_name]
            if dsn is not None:
                engine = create_engine(dsn)
                to_add = globals()[add_name]
                to_add._initialize(engine)
        _global_mappings.append(db_type)
    return Session()
