Exemplo n.º 1
0
    def get_kbr_values(self, searchkey="", searchvalue="", searchtype='s'):
        """
        Return dicts of 'key' and 'value' from a knowledge base.

        :param kb_name the name of the knowledge base
        :param searchkey search using this key
        :param searchvalue search using this value
        :param searchtype s=substring, e=exact, sw=startswith
        :return a list of dictionaries [{'key'=>x, 'value'=>y},..]
        """
        import warnings
        warnings.warn("The function is deprecated. Please use the "
                      "`KnwKBRVAL.query_kb_mappings()` instead. "
                      "E.g. [(kval.m_value,) for kval in "
                      "KnwKBRVAL.query_kb_mappings(kb_id).all()]")
        # prepare filters
        if searchtype == 's':
            searchkey = '%' + searchkey + '%'
        if searchtype == 's' and searchvalue:
            searchvalue = '%' + searchvalue + '%'
        if searchtype == 'sw' and searchvalue:  # startswith
            searchvalue = searchvalue + '%'
        if not searchvalue:
            searchvalue = '%'
        # execute query
        return db.session.execute(
            db.select([KnwKBRVAL.m_value],
                      db.and_(KnwKBRVAL.id_knwKB.like(self.id),
                              KnwKBRVAL.m_value.like(searchvalue),
                              KnwKBRVAL.m_key.like(searchkey))))
Exemplo n.º 2
0
    def get_kbr_values(self, searchkey="", searchvalue="", searchtype='s'):
        """
        Return dicts of 'key' and 'value' from a knowledge base.

        :param kb_name the name of the knowledge base
        :param searchkey search using this key
        :param searchvalue search using this value
        :param searchtype s=substring, e=exact, sw=startswith
        :return a list of dictionaries [{'key'=>x, 'value'=>y},..]
        """
        import warnings
        warnings.warn("The function is deprecated. Please use the "
                      "`KnwKBRVAL.query_kb_mappings()` instead. "
                      "E.g. [(kval.m_value,) for kval in "
                      "KnwKBRVAL.query_kb_mappings(kb_id).all()]")
        # prepare filters
        if searchtype == 's':
            searchkey = '%' + searchkey + '%'
        if searchtype == 's' and searchvalue:
            searchvalue = '%' + searchvalue + '%'
        if searchtype == 'sw' and searchvalue:  # startswith
            searchvalue = searchvalue + '%'
        if not searchvalue:
            searchvalue = '%'
        # execute query
        return db.session.execute(
            db.select([KnwKBRVAL.m_value],
                      db.and_(KnwKBRVAL.id_knwKB.like(self.id),
                              KnwKBRVAL.m_value.like(searchvalue),
                              KnwKBRVAL.m_key.like(searchkey))))
Exemplo n.º 3
0
def pre_upgrade():
    """Run pre-upgrade checks (optional)."""
    not_valid_nicknames = []
    for user in db.engine.execute(db.select([User.nickname])):
        if not User.check_nickname(user[0]):
            not_valid_nicknames.append(user[0])

    if len(not_valid_nicknames) > 0:
        list_users = ', '.join(not_valid_nicknames)
        raise RuntimeError(
            "These nicknames are not valid: {list_users}. "
            "Please fix them before continuing.".format(list_users=list_users))
def pre_upgrade():
    """Run pre-upgrade checks (optional)."""
    not_valid_nicknames = []
    for user in db.engine.execute(db.select([User.nickname])):
        if not User.check_nickname(user[0]):
            not_valid_nicknames.append(user[0])

    if len(not_valid_nicknames) > 0:
        list_users = ', '.join(not_valid_nicknames)
        raise RuntimeError(
            "These nicknames are not valid: {list_users}. "
            "Please fix them before continuing.".format(
                list_users=list_users)
        )
def __user_has_admin_role(self):
    from .local_config import CFG_ACC_ACTIVITIES_URLS
    return self.has_super_admin_role or db.object_session(self).query(
        db.func.count(User.id) > 0
    ).join(
        User.active_roles,
        UserAccROLE.role,
        AccROLE.authorizations
    ).filter(
        AccAuthorization.id_accACTION.in_(
            db.select([AccACTION.id]).where(
                AccACTION.name.in_(CFG_ACC_ACTIVITIES_URLS.keys())
            )
        ),
        User.id == self.id
    ).scalar()
Exemplo n.º 6
0
def add_kb(kb_name=u"Untitled", kb_type=None, tries=10):
    """Add a new kb in database, return the id.

    Add a new kb in database, and returns its id
    The name of the kb will be 'Untitled#'
    such that it is unique.

    :param kb_name: the name of the kb
    :param kb_type: the type of the kb, incl 'taxonomy' and 'dynamic'.
                   None for typical (leftside-rightside).
    :param tries: exit after <n> retry
    :return: the id of the newly created kb
    """
    created = False
    name = kb_name
    i = 0
    while (i < tries and created is False):
        try:
            kb = models.KnwKB(name=name, description="", kbtype=kb_type)
            created = True
            db.session.add(kb)
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            # get the highest id to calculate the new name
            result = db.session.execute(
                db.select([models.KnwKB.id]).order_by(db.desc(
                    models.KnwKB.id)).limit(1)).first()
            index = result[0] + 1 if result is not None else 1
            name = kb_name + " " + str(index)
            i = i + 1
            created = False
        except Exception:
            db.session.rollback()
            raise

    if created is False:
        # TODO raise the right exception
        raise Exception(
            _(
                "Can't create knowledge base \"%(name)s\".\n"
                "Probabily the server is busy! "
                "Try again later.",
                name=kb_name))

    return kb.id
Exemplo n.º 7
0
def add_kb(kb_name=u"Untitled", kb_type=None, tries=10):
    """Add a new kb in database, return the id.

    Add a new kb in database, and returns its id
    The name of the kb will be 'Untitled#'
    such that it is unique.

    :param kb_name: the name of the kb
    :param kb_type: the type of the kb, incl 'taxonomy' and 'dynamic'.
                   None for typical (leftside-rightside).
    :param tries: exit after <n> retry
    :return: the id of the newly created kb
    """
    created = False
    name = kb_name
    i = 0
    while(i < tries and created is False):
        try:
            kb = models.KnwKB(name=name, description="", kbtype=kb_type)
            created = True
            db.session.add(kb)
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            # get the highest id to calculate the new name
            result = db.session.execute(
                db.select([models.KnwKB.id])
                .order_by(db.desc(models.KnwKB.id))
                .limit(1)).first()
            index = result[0] + 1 if result is not None else 1
            name = kb_name + " " + str(index)
            i = i + 1
            created = False
        except Exception:
            db.session.rollback()
            raise

    if created is False:
        # TODO raise the right exception
        raise Exception(_("Can't create knowledge base \"%(name)s\".\n"
                          "Probabily the server is busy! "
                          "Try again later.", name=kb_name))

    return kb.id
Exemplo n.º 8
0
        UserAccROLE.expiration >= db.func.now()
    )
)

User.has_admin_role = property(
    lambda self:
    self.has_super_admin_role or db.object_session(self).query(
        db.func.count(User.id) > 0
    ).join(
        User.active_roles,
        UserAccROLE.role,
        AccROLE.authorizations
    ).filter(
        AccAuthorization.id_accACTION.in_(
            db.select([AccACTION.id]).where(
                AccACTION.name.in_(CFG_ACC_ACTIVITIES_URLS.keys())
            )
        ),
        User.id == self.id
    ).scalar()
)

User.has_super_admin_role = property(
    lambda self:
    db.object_session(self).query(db.func.count(User.id) > 0).join(
        User.active_roles,
        UserAccROLE.role
    ).filter(
        AccROLE.name == SUPERADMINROLE,
        User.id == self.id
    ).scalar()
 def record_count(cls):
     """TODO."""
     return db.select([db.func.count(WtgTAGRecord.id_bibrec)]) \
              .where(WtgTAGRecord.id_tag == cls.id) \
              .label('record_count')