Package org.molgenis.framework.db

Examples of org.molgenis.framework.db.QueryRule


    // first: add sorting of order by field
    if (getOrderByField() != null || "".equals(getOrderByField()))
    {
      logger.debug("adding order by on " + getOrderByField());
      if (getOrderByOperator().equals(Operator.SORTASC)) rules.add(new QueryRule(Operator.SORTASC,
          getOrderByField()));
      else
        rules.add(new QueryRule(Operator.SORTDESC, getOrderByField()));
    }

    // second: add sorting by primary key (ensuring predictable ordering)
    if (!getOrderByField().equals(primaryKeyField))
    {
      logger.debug("adding order by on " + primaryKeyField);
      if (getOrderByOperator().equals(Operator.SORTASC)) rules.add(new QueryRule(Operator.SORTASC,
          primaryKeyField));
      else
        rules.add(new QueryRule(Operator.SORTDESC, primaryKeyField));

    }

    // based on the pagingState we add additional filterings
    switch (pagingState)
    {
      case REFRESH:
        if (count > offset)
        {
          rules.add(new QueryRule(Operator.LIMIT, limit));
          rules.add(new QueryRule(getOrderByField(), Operator.GREATER_EQUAL, prevOrderByThreshold));
          if (!getOrderByField().equals(primaryKeyField)) rules.add(new QueryRule(primaryKeyField,
              Operator.GREATER_EQUAL, prevPKeyThreshold));
          // FIXME how can we distinguish page when sort field is not
          // unique!!
          logger.debug("loaded filters for refresh. Added operator: limit=" + limit + ", offset=" + offset);
          break;
        }
        else
        {
          logger.debug("refresh is delegated to 'last' operation because count < offset (maybe cause of deletes)");
          pagingState = State.LAST;
          this.refresh(db);
          return;
        }
      case NEXT:
        if (limit + offset < count)
        {
          offset = limit + offset;
          rules.add(new QueryRule(Operator.LIMIT, Math.min(limit, count - offset)));
          rules.add(new QueryRule(getOrderByField(), Operator.GREATER, nextOrderByThreshold));
          if (!getOrderByField().equals(primaryKeyField)) rules.add(new QueryRule(primaryKeyField,
              Operator.GREATER, nextPKeyThreshold));
          // FIXME how can we distinguish page when sort field is not
          // unique!!

          // get first from next threshold (exclusive)
          logger.debug("loaded filters for next. Added operator: " + getOrderByField() + " > "
              + nextOrderByThreshold + ". Offset is: " + offset + ") and " + primaryKeyField
              + " greater than: " + nextPKeyThreshold);
          break;
        }
        else
        // page in 'last' range, go last
        {
          pagingState = State.LAST;
          logger.debug("next, is already in 'last' range (offset=" + offset + "), refresh to last.");
          this.refresh(db);
          return;
        }
      case LAST:
        // get last, limit to remaining from count
        if (count % limit != 0) rules.add(new QueryRule(Operator.LIMIT, count % limit));
        else
          rules.add(new QueryRule(Operator.LIMIT, limit));
        if (count > limit) offset = (int) Math.round(Math.floor((count - 1) / limit) * limit);
        else
          offset = 0;
        rules.add(new QueryRule(Operator.LAST));
        logger.debug("loaded filters for last. Added operator: 'last'. Offset is: " + offset);
        break;
      case PREV:
        // get last before prev threshold (exclusive)
        // set it to be the previous valid offset
        if (offset - limit >= 0)
        {
          offset = offset - limit;
          rules.add(new QueryRule(Operator.LIMIT, limit));
          rules.add(new QueryRule(Operator.LAST));
          rules.add(new QueryRule(getOrderByField(), Operator.LESS, prevOrderByThreshold));
          if (!getOrderByField().equals(primaryKeyField)) rules.add(new QueryRule(primaryKeyField,
              Operator.LESS, prevPKeyThreshold));
          // FIXME how can we distinguish page when sort field is not
          // unique!!
          logger.debug("prev, offset: " + offset + ", " + getOrderByField() + " < " + prevOrderByThreshold
              + " and " + primaryKeyField + " greater than: " + prevPKeyThreshold);
          break;
        }
        else
        { // delegate to first
          logger.debug("prev, is already in 'first' range (offset=" + offset + "), refresh to first");
          pagingState = State.FIRST;
          this.refresh(db);
          return;
        }
      case FIRST:
        // get first, no additional filtering needed
        offset = 0;
        rules.add(new QueryRule(Operator.LIMIT, limit));
        logger.debug("loaded filters for first: no filters needed");
        break;
    }

    reloadPage(db, rules.toArray(new QueryRule[rules.size()]));
View Full Code Here


    List<QueryRule> rules = Arrays.asList(rul);

    Predicate whereClause = null;
    List<Order> orders = new ArrayList<Order>();

    QueryRule prevRule = null;

    forLoop: for (int i = 0; i < rules.size(); ++i)
    {
      QueryRule rule = rules.get(i);
      if (mapper != null)
      {
        rule.setField(mapper.getTableFieldName(rule.getField()));

        Operator operator = rule.getOperator();
        if (operator == Operator.SORTASC || operator == Operator.SORTDESC)
        {
          rule.setField(mapper.getTableFieldName(rule.getValue().toString()));
        }

        String attributeName = rule.getJpaAttribute();

        Predicate predicate = null;

        Expression<?> expression = _addJoin(rule, root, joinHash);

        Expression<?> lhs = null;
        if (expression != null)
        {
          lhs = expression;
        }
        else if (attributeName != null)
        {
          lhs = root.get(attributeName);
        }
        Object rhs = rule.getValue();

        switch (operator)
        {
          case LAST:
            throw new UnsupportedOperationException("Not supported yet.");
          case SORTASC:
            orders.add(cb.asc(lhs));
            break;
          case SORTDESC:
            orders.add(cb.desc(lhs));
            break;
          case LIMIT:
            limitOffset[0] = (Integer) rule.getValue();
            break;
          case OFFSET:
            limitOffset[1] = (Integer) rule.getValue();
            break;
          default:
            switch (operator)
            {
              case EQUALS:
                if (rhs instanceof Entity)
                {
                  try
                  {
                    predicate = cb.equal(root.get(attributeName), rule.getValue());
                  }
                  catch (Exception ex)
                  {
                    LogFactory.getLog(JPAQueryGeneratorUtil.class.getName()).error(ex);
                  }
                }
                else
                {
                  try
                  {
                    // it's a xref attribute which is joined
                    // to root
                    if (attributeName.contains(".")
                        || root.get(attributeName).getJavaType().getName()
                            .equals("java.util.List")
                        || root.get(attributeName).getJavaType().newInstance() instanceof Entity)
                    {
                      predicate = cb.equal(lhs, rhs);
                    }
                    else
                    { // normal attribute
                      predicate = cb.equal(lhs, rhs);
                    }
                  }
                  catch (InstantiationException ex)
                  {
                    // this is a hack, newInstance can not
                    // be called on inmutable object
                    // like Integer
                    predicate = cb.equal(lhs, rhs);
                  }
                  catch (IllegalAccessException ex)
                  {
                    LogFactory.getLog(JPAQueryGeneratorUtil.class.getName()).error(ex);
                    throw new DatabaseException(ex);
                  }
                }
                break;
              case NOT:
                predicate = cb.notEqual(lhs, rhs);
                break;
              case LIKE:
                if (lhs.getJavaType().getSimpleName().equals("String"))
                {
                  predicate = cb.like(lhs.as(String.class), (String) rhs);
                }
                else
                {
                  // TODO: What to do here?
                }
                break;
              case LESS:
                predicate = cb.lessThan((Expression) lhs, (Comparable<Object>) rhs);
                break;
              case GREATER:
                predicate = cb.greaterThan((Expression) lhs, (Comparable<Object>) rhs);
                break;
              case LESS_EQUAL:
                predicate = cb.lessThanOrEqualTo((Expression) lhs, (Comparable<Object>) rhs);
                break;
              case GREATER_EQUAL:
                predicate = cb.greaterThanOrEqualTo((Expression) lhs, (Comparable<Object>) rhs);
                break;
              case NESTED:
                QueryRule[] nestedrules = rule.getNestedRules();
                predicate = _createWhere(db, mapper, em, root, cq, cb, new int[2], joinHash,
                    nestedrules);
                break;
              case SUBQUERY:
                SubQueryRule sqr = (SubQueryRule) rule;

                Subquery sq = cq.subquery(sqr.getSubQueryResultClass());
                Root<IN> sqFrom = sq.from(sqr.getSubQueryFromClass());

                Mapper<IN> sqMapper = db.getMapper(sqr.getSubQueryFromClass().getName());

                Predicate where = _createWhere(db, sqMapper, em, sqFrom, cq, cb, new int[2], joinHash,
                    (QueryRule[]) sqr.getValue());
                sq.select(sqFrom.get(sqr.getSubQueryAttributeJpa())).where(where);

                // the operator of subquery should be handled in
                // the right way such that no code duplication
                // should occure
                // for the moment only in will work (more to
                // come)
                String fieldForSubQuery = sqr.getJpaAttribute();

                if (sqr.getSubQueryOperator().equals(Operator.IN))
                {
                  predicate = cb.in(root.get(fieldForSubQuery)).value(sq);
                }
                else
                {
                  throw new UnsupportedOperationException();
                }
                break;
              case IN: // not a query but a list for example
                    // SELECT * FROM
                // x WHERE x.a1 IN (v1, v2, v3)
                Object[] values = new Object[0];
                if (rule.getValue() instanceof List)
                {
                  values = ((List<?>) rule.getValue()).toArray();
                }
                else
                {
                  values = (Object[]) rule.getValue();
                }
                Class<?> attrClass = null;
                if (attributeName.contains("."))
                {
                  attrClass = lhs.getJavaType();
View Full Code Here

    List<QueryRule> rules = new ArrayList<QueryRule>();
    for (QueryRule rule : user_rules)
    {
      if (rule.getOperator() != null && rule.getOperator().equals(Operator.NESTED))
      {
        QueryRule r = new QueryRule(this.rewriteRules(db, rule.getNestedRules()));
        // r.setOr(rule.isOr());
        // rules.add(new QueryRule(Operator.AND));
        rules.add(r);
      }
      else
      {
        QueryRule r = this.rewriteMrefRule(db, rule);
        // r.setOr(rule.isOr());
        // rules.add(new QueryRule(Operator.OR));
        rules.add(r);
      }
    }
View Full Code Here

   * @throws DatabaseException
   */
  public String createWhereSql(boolean isNested, boolean withOffset, QueryRule... rules) throws DatabaseException
  {
    StringBuilder where_clause = new StringBuilder("");
    QueryRule previousRule = new QueryRule(Operator.AND);
    if (rules != null)
    {
      for (QueryRule r : rules)
      {
        // logger.debug(r);
        // skip OR and AND operators
        if (r.getOperator().equals(Operator.OR) || r.getOperator().equals(Operator.AND))
        {
          previousRule = r;
        }
        else
        {
          QueryRule rule = new QueryRule(r); // copy because of side
          // effects
          // logger.debug(rule);

          // String tablePrefix = "";
          rule.setField(getTableFieldName(rule.getField()));

          if (rule.getOperator() == Operator.LAST || rule.getOperator() == Operator.LIMIT
              || rule.getOperator() == Operator.OFFSET || rule.getOperator() == Operator.SORTASC
              || rule.getOperator() == Operator.SORTDESC)
          {

          }
          else if (rule.getOperator() == QueryRule.Operator.SEARCH)
          {
            // naive implementation, should use hibernate search
            // when it comes
            // available!
            List<QueryRule> searchRules = new ArrayList<QueryRule>();

            try
            {
              boolean addAND = false;

              // try create big OR filter for all fields and all
              // search elements
              // todo: enable string term concat using quotes
              if (rule.getValue() != null && !rule.getValue().equals("")) for (String term : rule
                  .getValue().toString().split(" "))
              {
                List<QueryRule> termRules = new ArrayList<QueryRule>();

                // create different query rule depending on type
                List<Field> fields = getDatabase().getMetaData()
                    .getEntity(create().getClass().getSimpleName()).getAllFields();

                for (Field f : fields)
                {
                  if (f.getType() instanceof StringField || f.getType() instanceof TextField)
                  {
                    // lowercase the term and field so
                    // matching becomes case insensitive
                    // e.g. SELECT * FROM web WHERE
                    // lower(metaDesc) LIKE
                    // '%dscript%tutorial%'
                    QueryRule searchQR = new QueryRule(f.getName(), Operator.LIKE, term.trim()
                        .toLowerCase());
                    searchQR.setField("lower(" + searchQR.getField() + ")");
                    termRules.add(searchQR);
                    termRules.add(new QueryRule(Operator.OR));
                  }
                }

                // add as big X or Y or Z subquery to our rules
                searchRules.add(new QueryRule(termRules));

                if (addAND) searchRules.add(new QueryRule(Operator.AND));
                addAND = true;
              }

              where_clause.append("(");
              where_clause.append(createWhereSql(true, false,
View Full Code Here

        }
      }

      for (QueryRule r : rules)
      {
        QueryRule rule = new QueryRule(r); // copy because of
                          // sideeffects

        // limit clause
        if ((rule.getOperator() == Operator.SORTASC && !revSort)
            || (revSort && rule.getOperator() == Operator.SORTDESC))
        {
          rule.setValue(getTableFieldName(rule.getValue().toString()));
          sort_clauseBuilder.append(rule.getValue().toString()).append(" ASC,");
        }
        else if ((rule.getOperator() == QueryRule.Operator.SORTDESC && !revSort)
            || (revSort && rule.getOperator() == Operator.SORTASC))
        {
          rule.setValue(getTableFieldName(rule.getValue().toString()));
          sort_clauseBuilder.append(rule.getValue().toString()).append(" DESC,");
        }
      }
    }
    if (sort_clauseBuilder.length() > 0) return " ORDER BY "
        + sort_clauseBuilder.substring(0, sort_clauseBuilder.lastIndexOf(","));
View Full Code Here

  }

  @Override
  public E findById(Object id) throws DatabaseException
  {
    List<E> result = find(new QueryRule(create().getIdField(), Operator.EQUALS, id));
    if (result.size() > 0) return result.get(0);
    return null;
  }
View Full Code Here

    when(tuple0.getColNames()).thenReturn(Arrays.asList("Name", "Continent")).getMock();
    when(tuple0.getString("Name")).thenReturn("Netherlands");

    Database db = mock(Database.class);
    String query = "SELECT Name, Continent FROM Country";
    QueryRule queryRule = new QueryRule("Code", Operator.EQUALS, "NLD");
    when(db.sql(query, queryRule)).thenReturn(Arrays.asList(tuple0));
    when(db.sql("SELECT COUNT(*) FROM Country", queryRule)).thenReturn(Arrays.asList(tuple0));

    TupleTable jdbcTable = new JdbcTable(db, query, Arrays.asList(queryRule));
    try
View Full Code Here

      String operatorStr = request.getString("__filter_operator" + suffix);
      Operator operator = QueryRule.Operator.valueOf(operatorStr);
      String filterValue = request.getString("__filter_value" + suffix);

      QueryRule filterRule;
      if (filterAttr.equals(FILTER_ATTRIBUTE_ALL))
      {
        filterRule = createFilterRule(db, operator, filterValue);
      }
      else
View Full Code Here

  QueryRule createFilterRule(Database db, String fieldName, Operator operator, String value)
      throws DatabaseException, MolgenisModelException
  {
    if (StringUtils.isEmpty(fieldName) || operator == null || StringUtils.isEmpty(value)) return null;

    QueryRule queryRule = null;
    for (Field field : getAllFields(db))
    {
      if (field.getName().equals(fieldName))
      {
        fieldName = getSearchField(fieldName);
        queryRule = new QueryRule(fieldName, operator, value);
        break;
      }
    }
    return queryRule;
  }
View Full Code Here

    List<QueryRule> queryRules = new ArrayList<QueryRule>();
    for (Field field : getAllFields(db))
    {
      String fieldName = getSearchField(field.getName());
      if (!queryRules.isEmpty()) queryRules.add(new QueryRule(Operator.OR));
      queryRules.add(new QueryRule(fieldName, operator, value));
    }
    return !queryRules.isEmpty() ? new QueryRule(queryRules) : null;
  }
View Full Code Here

TOP

Related Classes of org.molgenis.framework.db.QueryRule

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.