# Path: bitsd/common.py
# LOG = logging.getLogger('tornado.general')


from contextlib import contextmanager
from sqlalchemy import desc, create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker, scoped_session
from tornado.options import options
from bitsd.common import LOG
#: Global session and engine used by all engine methods.
#: Call `connect()` to initialize.
Session = None
Engine = None

def connect():
    """
    Open a connection to DB using parameters  from bitsd.conf and command line.
    """
    global Session, Engine
    Engine = create_engine(
        options.db_uri,
        pool_recycle=options.connection_recycle_timeout,
        echo=options.log_queries
    )
    session_factory = sessionmaker(bind=Engine)
    Session = scoped_session(session_factory)


@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = Session()
    try:
        yield session
        session.commit()
    except IntegrityError as e:
        LOG.error("Integrity error in DB, rolling back: %s", e)
        session.rollback()
    except:

# Path: bitsd/common.py
# LOG = logging.getLogger('tornado.general')


# Path: bitsd/persistence/engine.py
from contextlib import contextmanager
from sqlalchemy import desc, create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker, scoped_session
from tornado.options import options
from bitsd.common import LOG

#: Global session and engine used by all engine methods.
#: Call `connect()` to initialize.
Session = None
Engine = None

def connect():
    """
    Open a connection to DB using parameters  from bitsd.conf and command line.
    """
    global Session, Engine
    Engine = create_engine(
        options.db_uri,
        pool_recycle=options.connection_recycle_timeout,
        echo=options.log_queries
    )
    session_factory = sessionmaker(bind=Engine)
    Session = scoped_session(session_factory)


@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = Session()
    try:
        yield session
        session.commit()
    except IntegrityError as e:
        LOG.error("Integrity error in DB, rolling back: %s", e)
        session.rollback()
    except:

        LOG.error("Error in DB, rolling back.")