import traceback


def commit_changes(session, raise_exception=False):
    """
    Attempts to commit changes to DB
    - if it fails, error is logged and DB is rolled back

    Args:
    session (sqlalchemy.Session): session connected to DB

    Kargs:
    raise_exception (bool): if False, returns False instead of
                            raising exception
                            (default: False)

    Returns:
        (bool): True if successful commit else False
    """
    try:
        session.commit()
        return True
    except Exception as e:
        # write to error log file in npdb
        with open('io_error.log', 'a') as fid:
            fid.write(traceback.format_exc() + '\n\n')

        session.rollback()
        session.flush()

        if raise_exception:
            raise e
        return False