'Return a list of libraries from the DB.
:param  deleted: if True, show only ``deleted`` libraries, if False show only ``non-deleted``
:type   deleted: boolean (optional)
:returns: query that will emit all accessible libraries
:rtype: sqlalchemy query'

def list(self, trans, deleted=False):

    is_admin = trans.user_is_admin()
    query = trans.sa_session.query(trans.app.model.Library)
    if is_admin:
        if (deleted is None):
            pass
        elif deleted:
            query = query.filter((trans.app.model.Library.table.c.deleted == true()))
        else:
            query = query.filter((trans.app.model.Library.table.c.deleted == false()))
    else:
        current_user_role_ids = [role.id for role in trans.get_current_user_roles()]
        library_access_action = trans.app.security_agent.permitted_actions.LIBRARY_ACCESS.action
        restricted_library_ids = [lp.library_id for lp in trans.sa_session.query(trans.model.LibraryPermissions).filter((trans.model.LibraryPermissions.table.c.action == library_access_action)).distinct()]
        accessible_restricted_library_ids = [lp.library_id for lp in trans.sa_session.query(trans.model.LibraryPermissions).filter(and_((trans.model.LibraryPermissions.table.c.action == library_access_action), trans.model.LibraryPermissions.table.c.role_id.in_(current_user_role_ids)))]
        query = query.filter(or_(not_(trans.model.Library.table.c.id.in_(restricted_library_ids)), trans.model.Library.table.c.id.in_(accessible_restricted_library_ids)))
    return query
