import sqlalchemy
from sqlalchemy.orm import sessionmaker


class SQLManager(object):
    # Cache the database connection per application process.
    # More properly, this should be kept in thread-local state (threading.local()), but should suffice.
    # Each passed connection url will have its own pool.
    engines = {}

    @classmethod
    def get_sql_session_maker(cls, heroku_postgres_url, should_echo=False, cache=True):
        if not cache:
            return sessionmaker(bind=cls.connect(heroku_postgres_url, should_echo=should_echo))()
        else:
            engine = cls.engines.setdefault(heroku_postgres_url,
                                            cls.connect(heroku_postgres_url, should_echo=should_echo))

            return sessionmaker(bind=engine)()

    @staticmethod
    def connect(heroku_postgres_url, should_echo=False):
        if heroku_postgres_url:
            return sqlalchemy.create_engine(heroku_postgres_url, echo=should_echo)
        else:
            return sqlalchemy.create_engine('postgres://pivotal:@localhost/pivotal', echo=True)
