DOCUMENT ME!

@param cpoClass DOCUMENT ME!
@param sql DOCUMENT ME!
@param wheres DOCUMENT ME!
@param orderBy DOCUMENT ME!

@return DOCUMENT ME!

@throws org.synchronoss.cpo.CpoException DOCUMENT ME!
323473
protected <T> String buildSql(CpoClass cpoClass, String sql, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeQueries, List<BindAttribute> bindValues) throws CpoException {
    StringBuilder sqlText = new StringBuilder();

    sqlText.append(sql);

    if (wheres != null) {
      for (CpoWhere where : wheres) {
        BindableWhereBuilder<T> jwb = new BindableWhereBuilder<>(cpoClass);
        BindableCpoWhere jcw = (BindableCpoWhere) where;

        // do the where stuff here when ready
        try {
          jcw.acceptDFVisitor(jwb);
        } catch (Exception e) {
          throw new CpoException("Unable to build WHERE clause", e);
        }

        if (sqlText.indexOf(jcw.getName()) == -1) {
          sqlText.append(" ");
          sqlText.append(jwb.getWhereClause());
          bindValues.addAll(jwb.getBindValues());
        } else {
          sqlText = replaceMarker(sqlText, jcw.getName(), jwb, bindValues);
        }
      }
    }

    // do the order by stuff now
    if (orderBy != null) {
      HashMap<String, StringBuilder> mapOrderBy = new HashMap<>();
      try {
        for (CpoOrderBy ob : orderBy) {
          StringBuilder sb = mapOrderBy.get(ob.getMarker());
          if (sb == null) {
            sb = new StringBuilder(" ORDER BY ");
            mapOrderBy.put(ob.getMarker(), sb);
          } else {
            sb.append(",");
          }
          sb.append(ob.toString(cpoClass));
        }
      } catch (CpoException ce) {
        throw new CpoException("Error Processing OrderBy Attribute<" + ExceptionHelper.getLocalizedMessage(ce) + "> not Found. JDBC Expression=<" + sqlText.toString() + ">");
      }

      Set<Entry<String, StringBuilder>> entries = mapOrderBy.entrySet();
      for (Entry<String, StringBuilder> entry : entries) {
        if (sqlText.indexOf(entry.getKey()) == -1) {
          sqlText.append(entry.getValue().toString());
        } else {
          sqlText = replaceMarker(sqlText, entry.getKey(), entry.getValue().toString());
        }
      }
    }

    if (nativeQueries != null) {
      for (CpoNativeFunction cnq : nativeQueries) {
        if (cnq.getMarker() == null || sqlText.indexOf(cnq.getMarker()) == -1) {
          if (cnq.getExpression() != null && cnq.getExpression().length() > 0) {
            sqlText.append(" ");
            sqlText.append(cnq.getExpression());
          }
        } else {
          sqlText = replaceMarker(sqlText, cnq.getMarker(), cnq.getExpression());
        }
      }
    }

    // left for backwards compatibility
    sqlText = replaceMarker(sqlText, WHERE_MARKER, "");
    sqlText = replaceMarker(sqlText, ORDERBY_MARKER, "");

    return sqlText.toString();
  }
737235
protected <T> T processSelectGroup(T obj, String groupName, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions, Session sess) throws CpoException {
    T criteriaObj = obj;
    boolean recordsExist = false;
    Logger localLogger = obj == null ? logger : LoggerFactory.getLogger(obj.getClass());

    int recordCount = 0;
    int attributesSet = 0;

    T rObj = null;

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

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

      localLogger.info("=================== Class=<" + criteriaObj.getClass() + "> Type=<" + CpoAdapter.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) {

        CassandraBoundStatementFactory cbsf = new CassandraBoundStatementFactory(sess, this, cpoClass, cpoFunction, criteriaObj, wheres, orderBy, nativeExpressions);
        BoundStatement boundStatement = cbsf.getBoundStatement();

        // insertions on
        // selectgroup
        ResultSet rs = sess.execute(boundStatement);
        cbsf.release();

        ColumnDefinitions columnDefs = rs.getColumnDefinitions();

        if ((columnDefs.size() == 2) && "CPO_ATTRIBUTE".equalsIgnoreCase(columnDefs.getName(1)) && "CPO_VALUE".equalsIgnoreCase(columnDefs.getName(2))) {
          for(Row row : rs) {
            recordsExist = true;
            recordCount++;
            CpoAttribute attribute = cpoClass.getAttributeData(row.getString(0));

            if (attribute != null) {
              attribute.invokeSetter(rObj, new ResultSetCpoData(CassandraMethodMapper.getMethodMapper(), row, attribute, 1));
              attributesSet++;
            }
          }
        } else if (!rs.isExhausted()) {
          recordsExist = true;
          recordCount++;
          Row row = rs.one();
          for (int k = 0; k < columnDefs.size(); k++) {
            CpoAttribute attribute = cpoClass.getAttributeData(columnDefs.getName(k));

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

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

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

    return rObj;
  }
135515
private Query getFKQuery(Object obj, ClassDescriptor cld, CollectionDescriptor cds)
    {
        Query fkQuery;
        QueryByCriteria fkQueryCrit;

        if (cds.isMtoNRelation())
        {
            fkQueryCrit = getFKQueryMtoN(obj, cld, cds);
        }
        else
        {
            fkQueryCrit = getFKQuery1toN(obj, cld, cds);
        }

        // check if collection must be ordered
        if (!cds.getOrderBy().isEmpty())
        {
            Iterator iter = cds.getOrderBy().iterator();
            while (iter.hasNext())
            {
                fkQueryCrit.addOrderBy((FieldHelper)iter.next());
            }
        }

        // BRJ: customize the query
        if (cds.getQueryCustomizer() != null)
        {
            fkQuery = cds.getQueryCustomizer().customizeQuery(obj, pb, cds, fkQueryCrit);
        }
        else
        {
            fkQuery = fkQueryCrit;
        }

        return fkQuery;
    }
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));
        }
    }
307
public function selectAll($where=false, $order=false, $limit=false) {
        $clause = false;
        $values = array();
        if ( is_array($where) ) {
            $retval = self::extractWhere($where, $clause, $values);
            if ( is_string($retval) ) throw new \Exception($val);
        }
        $orderby = '';
        if ( is_string($order) ) {
            $orderby = self::extractOrder($order);
            if ( $orderby === false ) throw new \Exception('Invalid Order value');
        }

        $sql = "SELECT KVS.id AS id, json_body, KVS.created_at, KVS.updated_at
            FROM $this->KVS_TABLE AS KVS
            WHERE $this->KVS_FK_NAME = :foreign_key";
        if ( $clause ) $sql .= ' AND '.$clause;
        if ( $orderby ) $sql .= ' '.$orderby;
        $values[':foreign_key'] = $this->KVS_FK;
        $rows = $this->PDOX->allRowsDie($sql, $values);
        return $rows;
    }
565550
protected final <T> T executeQuery(final String sql, final StatementWithReturnBlock<T> queryBlock) throws Exception {
        checkState(initialized);

        setupConnection();
        checkNotNull(connection);
        boolean committed = false;
        try {
            T returnValue = withStatement(connection, sql, queryBlock);
            connection.commit();
            committed = true;
            return returnValue;
        } finally {
            if (!committed) {
                connection.rollback();
                cleanupConnection();
            }
        }
    }
1212951
public function getByOrder(string $orderBy, array $where = [], array $with = [], string $order = 'desc', int $limit = 0)
    {
        $query = $this->make($with);

        $query = $this->applyWhere($query, $where);

        $query = $query->orderBy($orderBy, $order);

        if ($limit) {
            $query = $query->take($limit);
        }

        return $query->get();
    }
281241
public OvhPaymentMethods order_orderId_paymentMethods_GET(Long orderId) throws IOException {
		String qPath = "/me/order/{orderId}/paymentMethods";
		StringBuilder sb = path(qPath, orderId);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhPaymentMethods.class);
	}
960981
protected function order_sql(?string $fieldname = null, string $order = 'ASC', ?string $tablealias = null) {

        if (!$tablealias) {
            $tablealias = 'analysable';
        }

        if ($order != 'ASC' && $order != 'DESC') {
            throw new \coding_exception('The order can only be ASC or DESC');
        }

        $ordersql = ' ORDER BY (CASE WHEN aua.timeanalysed IS NULL THEN 0 ELSE aua.timeanalysed END) ASC';
        if ($fieldname) {
            $ordersql .= ', ' . $tablealias . '.' . $fieldname .' ' . $order;
        }

        return $ordersql;
    }
848277
private function loadOrderQuery(): OrderVisitor
    {
        $logger = $this->getLogger();
        $query = new OrderQueryRequest();

        if ($wheres = $this->getDefaultWhere()) {
            $logger->debug('Added where-clause to fech orders.', ['predicates' => $wheres]);

            array_walk($wheres, function (string $where) use ($logger, $query) {
                $query->where($where);
            });
        } else {
            $logger->debug('No where-clause to fetch orders.');
        }

        $this->setOrderQuery($query);

        return $this;
    }
938721
public static Filter get(final IWhere _where, final IOrder _order, final Type... _baseTypes)
        throws CacheReloadException
    {
        return new Filter().analyze(_where, _order, Arrays.asList(_baseTypes));
    }
1043739
public <S> S queryOne(Class<S> type, String sql, Object[] params) {
        Connection conn = getConn();
        try {
            Query query = conn.createQuery(sql)
                    .withParams(params)
                    .setAutoDeriveColumnNames(true)
                    .throwOnMappingFailure(false);

            return ifReturn(AnimaUtils.isBasicType(type),
                    () -> query.executeScalar(type),
                    () -> query.executeAndFetchFirst(type));
        } finally {
            this.closeConn(conn);
            this.clean(null);
        }
    }
484409
@Override
	public SqlEntityQuery<E> desc(final String col, final Nulls nulls) {
		this.sortOrders.add(new SortOrder(col, Order.DESCENDING, nulls));
		return this;
	}
851904
public function buildSortingSQL(&$joins, &$where, &$sort, $order = 'ASC')
    {
        if ($this->isRandomOrder($order)) {
            $sort = 'ORDER BY RAND()';
        } else {
            $sort = sprintf(
                'ORDER BY (
                    SELECT %s
                    FROM tbl_entries_data_%d AS `ed`
                    WHERE entry_id = e.id
                ) %s, `e`.`id` %s',
                '`ed`.date',
                $this->get('id'),
                $order,
                $order
            );
        }
    }
411004
@PublicEvolving
	public PartitionOperator<T> withOrders(Order... orders) {
		Preconditions.checkState(pMethod == PartitionMethod.RANGE, "Orders cannot be applied for %s partition " +
				"method", pMethod);
		Preconditions.checkArgument(pKeys.getOriginalKeyFieldTypes().length == orders.length, "The number of key " +
				"fields and orders should be the same.");
		this.orders = orders;

		return this;
	}
633476
public WhereCondition WHERE(WhereCondition whereCondition) {
        checkTokenOrderIsCorrect(ESqlToken.WHERE);
        mSgSQL.append("(");
        mSgSQL.append(whereCondition.toWhereConditionPart());
        mSgSQL.append(")");
        return WhereCondition.this;
    }
972595
public function fieldSelectAll($table, $fields, $where, $orderBy = null)
    {
        $table = $this->getTableName($table);

        $query = "SELECT ";

        $query .= $this->selectFields($fields);

        $query .= " FROM " . $table . " ";

        $params = null;
        if ($where !== self::NO_WHERE_CLAUSE) {
            $query .= "WHERE " . $this->where($where, $params);
        }

        if ($orderBy) {
            $query .= $this->orderBy($orderBy) . " ";
        }

        return $this->query($query, $params);
    }