from contextlib import contextmanager
from dream_dtb import Session


class Singleton(type):
    """ Singleton metaclass implementation

    https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python#6798042
    """

    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = Session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()
