Process order by clause.

@param termsBuilder
the terms builder
@param orderByExpression
the order by expression
@param groupByClause
the group by clause
@param entityMetadata
the entity metadata
540513
private void processOrderByClause(TermsBuilder termsBuilder, Expression orderByExpression,
            Expression groupByClause, EntityMetadata entityMetadata)
    {
        Expression orderByClause = (OrderByClause) orderByExpression;
        OrderByItem orderByItems = (OrderByItem) ((OrderByClause) orderByClause).getOrderByItems();

        if (orderByClause instanceof CollectionExpression
                || !(orderByItems.getExpression().toParsedText().equalsIgnoreCase(groupByClause.toParsedText())))
        {
            logger.error("Order by and group by on different field are not supported simultaneously");
            throw new UnsupportedOperationException(
                    "Order by and group by on different field are not supported simultaneously");
        }

        String ordering = orderByItems.getOrdering().toString();
        termsBuilder.order(Terms.Order.term(!ordering.equalsIgnoreCase(Expression.DESC)));
    }
129240
private QueryBuilder getFilter(FilterClause clause, final EntityMetadata metadata)
    {
        String condition = clause.getCondition();
        Object value = condition.equals(Expression.IN) ? clause.getValue() : clause.getValue().get(0);
        String name = ((AbstractAttribute) ((MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                metadata.getPersistenceUnit())).entity(metadata.getEntityClazz()).getAttribute(clause.getProperty()))
                .getJPAColumnName();

        QueryBuilder filterBuilder = null;

        if (condition.equals(Expression.EQUAL))
        {
            filterBuilder = new TermQueryBuilder(name, value);
        }
        else if (condition.equals(Expression.GREATER_THAN))
        {
            filterBuilder = new RangeQueryBuilder(name).gt(value);
        }
        else if (condition.equals(Expression.LOWER_THAN))
        {
            filterBuilder = new RangeQueryBuilder(name).lt(value);
        }
        else if (condition.equals(Expression.GREATER_THAN_OR_EQUAL))
        {
            filterBuilder = new RangeQueryBuilder(name).gte(value);
        }
        else if (condition.equals(Expression.LOWER_THAN_OR_EQUAL))
        {
            filterBuilder = new RangeQueryBuilder(name).lte(value);
        }
        else if (condition.equals(Expression.DIFFERENT))
        {
            filterBuilder = new NotQueryBuilder(new TermQueryBuilder(name, value));
        }
        else if (condition.equals(Expression.IN))
        {
            filterBuilder = new TermsQueryBuilder(name, clause.getValue());
        }

        return filterBuilder;
    }
39088
public void setOrderBy(OrderBy ordering) throws TupleMRException {
    failIfNull(ordering, "OrderBy can't be null");
    failIfEmpty(ordering.getElements(), "OrderBy can't be empty");
    failIfEmpty(schemas, "Need to specify source schemas");
    failIfEmpty(groupByFields, "Need to specify group by fields");
    if (schemas.size() == 1) {
      if (ordering.getSchemaOrderIndex() != null) {
        throw new TupleMRException(
            "Not able to use source order when just one source specified");
      }
    }
    Schema firstSchema = schemas.get(0);

    for (SortElement sortElement : ordering.getElements()) {
      if (!fieldPresentInAllSchemas(sortElement.getName())) {
        throw new TupleMRException("Can't sort by field '" + sortElement.getName()
            + "' . Not present in all sources");
      }
      if (!fieldSameTypeInAllSources(sortElement.getName())) {
        throw new TupleMRException("Can't sort by field '" + sortElement.getName()
            + "' since its type differs among sources");
      }

      if (sortElement.getCustomComparator() != null) {
        Field field = firstSchema.getField(sortElement.getName());
        if (field.getType() != Type.OBJECT) {
          throw new TupleMRException("Not allowed to specify custom comparator for type=" + field.getType());
        }
      }
    }
    // group by fields need to be a prefix of sort by fields
    for (String groupField : groupByFields) {
      if (!ordering.containsBeforeSchemaOrder(groupField)) {
        throw new TupleMRException("Group by field '" + groupField
            + "' is not present in common order by before source order");
      }
    }

    this.commonOrderBy = ordering;
  }
1283291
protected <T> long processUpdateGroup(T obj, String groupType, String groupName, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions, Connection con) throws CpoException {
    Logger localLogger = obj == null ? logger : LoggerFactory.getLogger(obj.getClass());
    CpoClass cpoClass;
    PreparedStatement ps = null;

    JdbcPreparedStatementFactory jpsf = null;
    long updateCount = 0;

    if (obj == null) {
      throw new CpoException("NULL Object passed into insertObject, deleteObject, updateObject, or persistObject");
    }

    try {
      cpoClass = metaDescriptor.getMetaClass(obj);
      List<CpoFunction> cpoFunctions = cpoClass.getFunctionGroup(getGroupType(obj, groupType, groupName, con), groupName).getFunctions();
      localLogger.info("=================== Class=<" + obj.getClass() + "> Type=<" + groupType + "> Name=<" + groupName + "> =========================");

      int numRows = 0;

      for (CpoFunction cpoFunction : cpoFunctions) {
        jpsf = new JdbcPreparedStatementFactory(con, this, cpoClass, cpoFunction, obj, wheres, orderBy, nativeExpressions);
        ps = jpsf.getPreparedStatement();
        numRows += ps.executeUpdate();
        jpsf.release();
        ps.close();
      }
      localLogger.info("=================== " + numRows + " Updates - Class=<" + obj.getClass() + "> Type=<" + groupType + "> Name=<" + groupName + "> =========================");

      if (numRows > 0) {
        updateCount++;
      }
    } catch (Throwable t) {
      String msg = "ProcessUpdateGroup failed:" + groupType + "," + groupName + "," + obj.getClass().getName();
      // TODO FIX THIS
      // localLogger.error("bound values:" + this.parameterToString(jq));
      localLogger.error(msg, t);
      throw new CpoException(msg, t);
    } finally {
      statementClose(ps);
      if (jpsf != null) {
        jpsf.release();
      }
    }

    return updateCount;
  }
1341205
protected <T> long processUpdateGroup(T obj, String groupType, String groupName, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions, Session sess) throws CpoException {
    Logger localLogger = obj == null ? logger : LoggerFactory.getLogger(obj.getClass());
    CpoClass cpoClass;

    if (obj == null) {
      throw new CpoException("NULL Object passed into insertObject, deleteObject, updateObject, or persistObject");
    }

    try {
      cpoClass = metaDescriptor.getMetaClass(obj);
      List<CpoFunction> cpoFunctions = cpoClass.getFunctionGroup(getGroupType(obj, groupType, groupName, sess), groupName).getFunctions();
      localLogger.info("=================== Class=<" + obj.getClass() + "> Type=<" + groupType + "> Name=<" + groupName + "> =========================");

      for (CpoFunction cpoFunction : cpoFunctions) {
        CassandraBoundStatementFactory boundStatementFactory = new CassandraBoundStatementFactory(sess, this, cpoClass, cpoFunction, obj, wheres, orderBy, nativeExpressions);
        executeBoundStatement(sess, boundStatementFactory);
      }
      localLogger.info("=================== " + " Updates - Class=<" + obj.getClass() + "> Type=<" + groupType + "> Name=<" + groupName + "> =========================");
    } catch (Throwable t) {
      String msg = "ProcessUpdateGroup failed:" + groupType + "," + groupName + "," + obj.getClass().getName();
      // TODO FIX THIS
      // localLogger.error("bound values:" + this.parameterToString(jq));
      localLogger.error(msg, t);
      throw new CpoException(msg, t);
    }

    return unknownModifyCount;
  }
395815
@Override
    public boolean isOrderDeterministic() {
        if ( ! hasTopLevelScans()) {
            // This currently applies to parent queries that do all their
            // scanning in subqueries and so take on the order determinism of
            // their subqueries. This might have to be rethought to allow
            // ordering in parent queries to effect determinism of unordered
            // "FROM CLAUSE" subquery results.
            return true;
        }

        if (hasAOneRowResult()) {
            return true;
        }

        if ( ! hasOrderByColumns() ) {
            return false;
        }

        // The nonOrdered expression list is used as a short-cut
        // -- if an expression has been determined to be
        // non-ordered when encountered as a GROUP BY expression,
        // it will also be non-ordered when encountered in the select list.
        ArrayList<AbstractExpression> nonOrdered = new ArrayList<>();

        if (isGrouped()) {
            // Does the ordering of a statements's GROUP BY columns
            // ensure determinism?
            // All display columns and order-by expressions
            // are functionally dependent on the GROUP BY
            // columns even if the display column's values
            // are not ordered or unique,
            // so ordering by ALL of the GROUP BY columns is enough
            // to get full determinism,
            // EVEN if ordering by other (dependent) expressions,
            // regardless of the placement of non-GROUP BY expressions
            // in the ORDER BY list.
            if (orderByColumnsDetermineAllColumns(m_groupByColumns, nonOrdered)) {
                return true;
            }

            if (orderByColumnsDetermineAllDisplayColumns(nonOrdered)) {
                return true;
            }

        }
        else {
            if (orderByColumnsDetermineAllDisplayColumns(nonOrdered)) {
                return true;
            }

            if (orderByColumnsCoverUniqueKeys()) {
                return true;
            }
        }
        return false;
    }
396161
public final function FirstByField($field, $value, Sql\OrderList $orderBy = null, Sql\GroupList $groupBy = null)
    {
        $result = $this->FetchByField(false, $field, $value, $orderBy, $groupBy, 0, 1);
        if (count($result))
            return $result[0];
    }
395968
public Query groupby(final Collection<? extends Expression> groupbyColumns) {
        if (groupbyColumns == null) {
            return this;
        }

        this.groupbyColumns.addAll(groupbyColumns);

        return this;
    }
741961
protected <T> T processSelectGroup(T obj, String groupName, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions, Connection con) throws CpoException {
    PreparedStatement ps = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd;
    CpoClass cpoClass;
    JdbcCpoAttribute attribute;
    T criteriaObj = obj;
    boolean recordsExist = false;
    Logger localLogger = obj == null ? logger : LoggerFactory.getLogger(obj.getClass());

    int recordCount = 0;
    int attributesSet = 0;

    int k;
    T rObj = null;

    if (obj == null) {
      throw new CpoException("NULL Object passed into retrieveBean");
    }

    try {
      cpoClass = metaDescriptor.getMetaClass(criteriaObj);
      List<CpoFunction> functions = cpoClass.getFunctionGroup(JdbcCpoAdapter.RETRIEVE_GROUP, groupName).getFunctions();

      localLogger.info("=================== Class=<" + criteriaObj.getClass() + "> Type=<" + JdbcCpoAdapter.RETRIEVE_GROUP + "> Name=<" + groupName + "> =========================");

      try {
        rObj = (T) obj.getClass().newInstance();
      } catch (IllegalAccessException iae) {
        localLogger.error("=================== Could not access default constructor for Class=<" + obj.getClass() + "> ==================");
        throw new CpoException("Unable to access the constructor of the Return Object", iae);
      } catch (InstantiationException iae) {
        throw new CpoException("Unable to instantiate Return Object", iae);
      }

      for (CpoFunction cpoFunction : functions) {

        JdbcPreparedStatementFactory jpsf = new JdbcPreparedStatementFactory(con, this, cpoClass, cpoFunction, criteriaObj, wheres, orderBy, nativeExpressions);
        ps = jpsf.getPreparedStatement();

        // insertions on
        // selectgroup
        rs = ps.executeQuery();
        jpsf.release();

        if (rs.isBeforeFirst()) {
          rsmd = rs.getMetaData();

          if ((rsmd.getColumnCount() == 2) && "CPO_ATTRIBUTE".equalsIgnoreCase(rsmd.getColumnLabel(1)) && "CPO_VALUE".equalsIgnoreCase(rsmd.getColumnLabel(2))) {
            while (rs.next()) {
              recordsExist = true;
              recordCount++;
              attribute = (JdbcCpoAttribute) cpoClass.getAttributeData(rs.getString(1));

              if (attribute != null) {
                attribute.invokeSetter(rObj, new ResultSetCpoData(JdbcMethodMapper.getMethodMapper(), rs, attribute, 2));
                attributesSet++;
              }
            }
          } else if (rs.next()) {
            recordsExist = true;
            recordCount++;
            for (k = 1; k <= rsmd.getColumnCount(); k++) {
              attribute = (JdbcCpoAttribute) cpoClass.getAttributeData(rsmd.getColumnLabel(k));

              if (attribute != null) {
                attribute.invokeSetter(rObj, new ResultSetCpoData(JdbcMethodMapper.getMethodMapper(), rs, attribute, k));
                attributesSet++;
              }
            }

            if (rs.next()) {
              String msg = "ProcessSelectGroup(Object, String) failed: Multiple Records Returned";
              localLogger.error(msg);
              throw new CpoException(msg);
            }
          }
          criteriaObj = rObj;
        }

        rs.close();
        rs = null;
        ps.close();
        ps = null;
      }

      if (!recordsExist) {
        rObj = null;
        localLogger.info("=================== 0 Records - 0 Attributes - Class=<" + criteriaObj.getClass() + "> Type=<" + JdbcCpoAdapter.RETRIEVE_GROUP + "> Name=<" + groupName + "> =========================");
      } else {
        localLogger.info("=================== " + recordCount + " Records - " + attributesSet + " Attributes - Class=<" + criteriaObj.getClass() + ">  Type=<" + JdbcCpoAdapter.RETRIEVE_GROUP + "> Name=<" + groupName + "> =========================");
      }
    } catch (Throwable t) {
      String msg = "ProcessSeclectGroup(Object) failed: " + ExceptionHelper.getLocalizedMessage(t);
      localLogger.error(msg, t);
      rObj = null;
      throw new CpoException(msg, t);
    } finally {
      resultSetClose(rs);
      statementClose(ps);
    }

    return rObj;
  }
765110
@Override
	public AppEngineGetList<E> sort(Order<?, ?>... orders) {
		if (orders == null) {
			throw new IllegalArgumentException("'orders' must not be [" + orders + "]");
		}
		
		this.orders = Arrays.asList(orders);
		return this;
	}
393065
public function sortable(
        array $orderColumns = [],
        string $orderByKey = 'order_by',
        string $directionKey = 'direction'
    ): void {
        $model = $this->resolveQueryBuilderFromModel($this->model);
        $request = $this->app->make('request');

        $orderByValue = $request->input($orderByKey);
        $directionValue = $request->input($directionKey);

        $this->set('filter.order_by', ['key' => $orderByKey, 'value' => $orderByValue]);
        $this->set('filter.direction', ['key' => $directionKey, 'value' => $directionValue]);
        $this->set('filter.columns', $orderColumns);

        $this->model = $this->setupBasicQueryFilter($model, [
            'order_by' => $orderByValue,
            'direction' => $directionValue,
            'columns' => $orderColumns,
        ]);
    }
837046
private void buildOrderBy(final StringBuilder orderByBuilder, final Map<String, SortDirection> sorts) {
        boolean isFirst = true;
        String querySortDirection;

        for (final Map.Entry<String, SortDirection> sort : sorts.entrySet()) {
            if (isFirst) {
                orderByBuilder.append(" ORDER BY ");
                isFirst = false;
            } else {
                orderByBuilder.append(", ");
            }

            if (sort.getValue().equals(SortDirection.ASCENDING)) {
                querySortDirection = "ASC";
            } else {
                querySortDirection = "DESC";
            }
            orderByBuilder.append(sort.getKey()).append(" ").append(querySortDirection);
        }
    }
677459
private Group[] orderGroup(List<Group> groups, String[] groupsOrder) {
        LinkedList<Group> groupsOrdered = new LinkedList();

        List<Group> remained = new ArrayList(groups);

        for (String order : groupsOrder) {
            for (Group remain : remained) {
                if (remain.title.equals(order)) {
                    groupsOrdered.add(remain);
                    remained.remove(remain);
                    break;
                }
            }
        }

        groupsOrdered.addAll(remained);

        return groupsOrdered.toArray(new Group[groupsOrdered.size()]);
    }
1088011
private StringBuilder appendOrderByClause(MetamodelImpl metaModel, EntityMetadata m, EmbeddableType keyObj,
        StringBuilder builder, CQLTranslator translator) {
        List<SortOrdering> orders = getKunderaQuery().getOrdering();

        if (orders != null) {
            builder.append(CQLTranslator.SPACE_STRING);
            builder.append(CQLTranslator.SORT_CLAUSE);

            for (SortOrdering order : orders) {
                String orderColumnName = order.getColumnName();

                orderColumnName = orderColumnName.substring(orderColumnName.indexOf(".") + 1, orderColumnName.length());

                String orderByColumnName;

                if (StringUtils.contains(orderColumnName, '.')) {
                    String propertyName = orderColumnName.substring(0, orderColumnName.indexOf("."));
                    Attribute embeddableAttribute = metaModel.getEntityAttribute(m.getEntityClazz(), propertyName);
                    EmbeddableType embeddableType =
                        metaModel.embeddable(((AbstractAttribute) embeddableAttribute).getBindableJavaType());
                    orderColumnName = orderColumnName.substring(orderColumnName.indexOf(".") + 1);
                    AbstractAttribute attribute = (AbstractAttribute) embeddableType.getAttribute(orderColumnName);
                    orderByColumnName = attribute.getJPAColumnName();

                } else {
                    Attribute attribute = metaModel.getEntityAttribute(m.getEntityClazz(), orderColumnName);
                    orderByColumnName = ((AbstractAttribute) attribute).getJPAColumnName();
                }

                builder = translator.ensureCase(builder, orderByColumnName, false);
                builder.append(CQLTranslator.SPACE_STRING);
                builder.append(order.getOrder());
                builder.append(CQLTranslator.COMMA_STR);
            }

            if (!orders.isEmpty()) {
                builder.deleteCharAt(builder.lastIndexOf(CQLTranslator.COMMA_STR));
            }
        }
        return builder;
    }
140859
def order_by(self, **kwargs):
        
        if kwargs:
            col, order = kwargs.popitem()
            self.order_clause = "order by {col} {order} ".format(
                col=col, order=order)
        return self
1124444
protected <T> long processBatchUpdateGroup(T[] arr, String groupType, String groupName, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions, Connection con) throws CpoException {
    CpoClass jmc;
    List<CpoFunction> cpoFunctions;
    PreparedStatement ps = null;
    CpoFunction cpoFunction;
    JdbcPreparedStatementFactory jpsf = null;
    long updateCount = 0;
    int[] updates;
    Logger localLogger = logger;

    try {
      jmc = metaDescriptor.getMetaClass(arr[0]);
      cpoFunctions = jmc.getFunctionGroup(getGroupType(arr[0], groupType, groupName, con), groupName).getFunctions();
      localLogger = LoggerFactory.getLogger(jmc.getMetaClass());

      int numRows = 0;

      // Only Batch if there is only one function
      if (cpoFunctions.size() == 1) {
        localLogger.info("=================== BATCH - Class=<" + arr[0].getClass() + "> Type=<" + groupType + "> Name=<" + groupName + "> =========================");
        cpoFunction = cpoFunctions.get(0);
        jpsf = new JdbcPreparedStatementFactory(con, this, jmc, cpoFunction, arr[0], wheres, orderBy, nativeExpressions);
        ps = jpsf.getPreparedStatement();
        ps.addBatch();
        for (int j = 1; j < arr.length; j++) {
//          jpsf.bindParameters(arr[j]);
          jpsf.setBindValues(jpsf.getBindValues(cpoFunction, arr[j]));
          ps.addBatch();
        }
        updates = ps.executeBatch();
        jpsf.release();
        ps.close();
        for (int update : updates) {
          if (update < 0 && update == PreparedStatement.SUCCESS_NO_INFO) {
            // something updated but we do not know what or how many so default to one.
            numRows++;
          } else {
            numRows += update;
          }
        }
        localLogger.info("=================== BATCH - " + numRows + " Updates - Class=<" + arr[0].getClass() + "> Type=<" + groupType + "> Name=<" + groupName + "> =========================");
      } else {
        localLogger.info("=================== Class=<" + arr[0].getClass() + "> Type=<" + groupType + "> Name=<" + groupName + "> =========================");
        for (T obj : arr) {
          for (CpoFunction function : cpoFunctions) {
            jpsf = new JdbcPreparedStatementFactory(con, this, jmc, function, obj, wheres, orderBy, nativeExpressions);
            ps = jpsf.getPreparedStatement();
            numRows += ps.executeUpdate();
            jpsf.release();
            ps.close();
          }
        }
        localLogger.info("=================== " + numRows + " Updates - Class=<" + arr[0].getClass() + "> Type=<" + groupType + "> Name=<" + groupName + "> =========================");
      }

      if (numRows > 0) {
        updateCount = numRows;
      }
    } catch (Throwable t) {
      String msg = "ProcessUpdateGroup failed:" + groupType + "," + groupName + "," + arr[0].getClass().getName();
      // TODO FIX This
      // localLogger.error("bound values:" + this.parameterToString(jq));
      localLogger.error(msg, t);
      throw new CpoException(msg, t);
    } finally {
      statementClose(ps);
      if (jpsf != null) {
        jpsf.release();
      }
    }

    return updateCount;
  }
267724
private static void addOrder(Criteria c, String sort, String order, boolean ignoreCase) {
        if (ORDER_DESC.equals(order)) {
            c.addOrder(ignoreCase ? Order.desc(sort).ignoreCase() : Order.desc(sort));
        }
        else {
            c.addOrder(ignoreCase ? Order.asc(sort).ignoreCase() : Order.asc(sort));
        }
    }