Builds where Clause.

@param kunderaQuery
the kundera query
@param metadata
the metadata
@param metaModel
the meta model
@param translator
the translator
@param builder
the builder
420525
private void buildWhereClause(KunderaQuery kunderaQuery, EntityMetadata metadata, MetamodelImpl metaModel,
        CQLTranslator translator, StringBuilder builder) {
        for (Object clause : kunderaQuery.getFilterClauseQueue()) {
            FilterClause filterClause = (FilterClause) clause;
            Field f = (Field) metaModel.entity(metadata.getEntityClazz())
                .getAttribute(metadata.getFieldName(filterClause.getProperty())).getJavaMember();
            String jpaColumnName = getColumnName(metadata, filterClause.getProperty());

            if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {
                Field[] fields = metadata.getIdAttribute().getBindableJavaType().getDeclaredFields();
                EmbeddableType compoundKey = metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType());
                for (Field field : fields) {
                    if (field != null && !Modifier.isStatic(field.getModifiers())
                        && !Modifier.isTransient(field.getModifiers()) && !field.isAnnotationPresent(Transient.class)) {
                        Attribute attribute = compoundKey.getAttribute(field.getName());
                        String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
                        Object value = PropertyAccessorHelper.getObject(filterClause.getValue().get(0), field);
                        // TODO
                        translator.buildWhereClause(builder, field.getType(), columnName, value,
                            filterClause.getCondition(), false);
                    }
                }
            } else {
                translator.buildWhereClause(builder, f.getType(), jpaColumnName, filterClause.getValue().get(0),
                    filterClause.getCondition(), false);
            }
        }
        builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());
    }
853795
public function where($key, $operator = null, $value = null): IQueryBuilderHandler
    {
        // If two params are given then assume operator is =
        if (\func_num_args() === 2) {
            $value = $operator;
            $operator = '=';
        }

        if (\is_bool($value) === true) {
            $value = (int)$value;
        }

        return $this->whereHandler($key, $operator, $value);
    }
930289
private void parseAndBuildFilters(EntityType entityType, KuduScannerBuilder scannerBuilder, Expression whereExp)
    {
        if (whereExp instanceof ComparisonExpression)
        {
            String left = ((ComparisonExpression) whereExp).getLeftExpression().toActualText();

            String right = ((ComparisonExpression) whereExp).getRightExpression().toActualText();
            if (right.startsWith(POSITIONAL_PREFIX) || right.startsWith(PARAMETERIZED_PREFIX))
            {
                right = kunderaQuery.getParametersMap().get(right) + "";
            }
            Attribute attribute = entityType.getAttribute(left.split(DOT_REGEX)[1]);
            addColumnRangePredicateToBuilder((Field) attribute.getJavaMember(), scannerBuilder,
                    ((AbstractAttribute) attribute).getJPAColumnName(), right,
                    ((ComparisonExpression) whereExp).getActualIdentifier());
        }
        else if (whereExp instanceof AndExpression)
        {
            parseAndBuildFilters(entityType, scannerBuilder, ((AndExpression) whereExp).getLeftExpression());
            parseAndBuildFilters(entityType, scannerBuilder, ((AndExpression) whereExp).getRightExpression());
        }
        else if (whereExp instanceof InExpression)
        {

            ListIterator<Expression> inIter = ((InExpression) whereExp).getInItems().children().iterator();
            Attribute attribute = entityType.getAttribute(((InExpression) whereExp).getExpression().toActualText()
                    .split(DOT_REGEX)[1]);
            addInPredicateToBuilder(scannerBuilder, inIter, attribute);
        }

        else
        {
            logger.error("Operation not supported");
            throw new KunderaException("Operation not supported");
        }
    }
1018330
private QueryBuilder populateLikeQuery(LikeExpression likeExpression, EntityMetadata metadata)
    {
        Expression patternValue = likeExpression.getPatternValue();
        String field = likeExpression.getStringExpression().toString();

        String likePattern = (patternValue instanceof InputParameter) ? kunderaQuery.getParametersMap()
                .get((patternValue).toParsedText()).toString() : patternValue.toParsedText().toString();
        String jpaField = getField(field);

        log.debug("Pattern value for field " + field + " is: " + patternValue);
        QueryBuilder filterBuilder = getQueryBuilder(kunderaQuery.new FilterClause(jpaField, Expression.LIKE,
                likePattern, field), metadata);

        return filterBuilder;
    }
104790
public static function findByMetadataQueryBuilder(
        QueryBuilder $qb,
        $join,
        array $metadata,
        $alias = 'metadata',
        $operator = 'eq',
        $whereOperator = 'and'
    ) {
        $qb->join($join, $alias);

        foreach ($metadata as $key => $data) {
            $andX = $qb->expr()->andX();

            foreach ($data as $field => $value) {
                $itemOperator = $operator;

                if (is_array($value)) {
                    $value = $value['value'];
                    $itemOperator = $value['operator'];
                }

                $parameterName = sprintf('%s_%s_%s', $alias, $field, $key);
                $andX->add(call_user_func_array(
                    array($qb->expr(), $itemOperator),
                    array(
                        sprintf('%s.%s', $alias, $field),
                        sprintf(':%s', $parameterName),
                    )
                ));

                $qb->setParameter($parameterName, $value);
            }

            call_user_func_array(array($qb, sprintf('%sWhere', $whereOperator)), array($andX));
        }

        return $qb;
    }
1368844
private List buildRecords(InternalAggregations internalAgg, SearchHits topHits, KunderaQuery query,
            MetamodelImpl metaModel, Class clazz, EntityMetadata entityMetadata)
    {
        List temp = new ArrayList<>();

        Iterator<Expression> orderIterator = getSelectExpressionOrder(query).iterator();
        while (orderIterator.hasNext())
        {
            Expression exp = orderIterator.next();
            String text = exp.toActualText();
            String field = KunderaQueryUtils.isAggregatedExpression(exp) ? text.substring(
                    text.indexOf(ESConstants.DOT) + 1, text.indexOf(ESConstants.RIGHT_BRACKET)) : text.substring(
                    text.indexOf(ESConstants.DOT) + 1, text.length());

            temp.add(KunderaQueryUtils.isAggregatedExpression(exp) ? getAggregatedResult(internalAgg,
                    ((AggregateFunction) exp).getIdentifier(), exp) : getFirstResult(query, field, topHits, clazz,
                    metaModel, entityMetadata));
        }
        return temp;
    }
317751
public AggregationBuilder buildAggregation(KunderaQuery query, EntityMetadata entityMetadata, QueryBuilder filter)
    {
        SelectStatement selectStatement = query.getSelectStatement();

        // To apply filter for where clause
        AggregationBuilder aggregationBuilder = buildWhereAggregations(entityMetadata, filter);
        if (KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))
        {
            TermsBuilder termsBuilder = processGroupByClause(selectStatement.getGroupByClause(), entityMetadata, query);
            aggregationBuilder.subAggregation(termsBuilder);
        }
        else
        {
            if (KunderaQueryUtils.hasHaving(query.getJpqlExpression()))
            {
                logger.error("Identified having clause without group by, Throwing not supported operation Exception");
                throw new UnsupportedOperationException(
                        "Currently, Having clause without group by caluse is not supported.");
            }
            else
            {
                aggregationBuilder = (selectStatement != null) ? query.isAggregated() ? buildSelectAggregations(
                        aggregationBuilder, selectStatement, entityMetadata) : null : null;
            }
        }

        return aggregationBuilder;
    }
646750
protected <T, K extends Serializable>
    Query<T> _buildQuery(
                    final DAO<T, K>  dao,
                    final Class<T> type,
                    final QueryParams params
                    )
    {
        Query<T>  query = null;
        try {
            query = dao.createQuery();
            QueryBuilder  builder = _getQueryBuilderFactory().newBuilder( type );
            query = builder.build( query, params );
        } catch (RepositoryConfigurationException ex) {
            throw ex;
        } catch (QueryException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new QueryException( ex );
        }

        return query;
    }
423299
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        RethinkDB r = ((RethinkDBClient) client).getR();
        Connection conn = ((RethinkDBClient) client).getConnection();

        Filter filter = null;
        Pluck pluck;
        Table table = r.db(m.getSchema()).table(m.getTableName());

        Cursor cursor = null;
        List results = new ArrayList();

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                .getMetamodel(m.getPersistenceUnit());
        EntityType entityType = metaModel.entity(m.getEntityClazz());

        JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();
        List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);

        if (KunderaQueryUtils.hasWhereClause(jpqlExp))
        {
            // add filters
            WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);
            Expression whereExp = whereClause.getConditionalExpression();
            filter = table.filter(parseAndBuildFilters(entityType, whereExp));
        }

        if (!selectColumns.isEmpty())
        {
            // select by specific columns, consider last for plucking
            pluck = filter == null ? table.pluck(selectColumns) : filter.pluck(selectColumns);
            cursor = pluck.run(conn);
        }

        if (cursor == null)
        {
            cursor = (Cursor) (filter == null ? table.run(conn) : filter.run(conn));
        }

        for (Object obj : cursor)
        {
            Object entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());
            buildEntityFromCursor(entity, (HashMap) obj, entityType);
            results.add(entity);
        }

        return results;
    }
1104352
protected String buildDeleteSQL(final TableMetadata metadata, final Class<? extends Object> type,
			final SqlConfig sqlConfig, final boolean addCondition) {
		StringBuilder sql = new StringBuilder("DELETE ").append("/* ")
				.append(sqlConfig.getSqlAgentFactory().getSqlIdKeyName()).append(" */")
				.append(" FROM ").append(metadata.getTableIdentifier()).append("").append(System.lineSeparator());

		if (addCondition) {
			boolean firstFlag = true;
			sql.append("WHERE").append(System.lineSeparator());

			List<? extends Column> cols = !metadata.getKeyColumns().isEmpty() ? metadata.getKeyColumns()
					: Arrays
							.asList(metadata.getColumns().get(0));
			for (TableMetadata.Column col : cols) {
				StringBuilder parts = new StringBuilder().append("\t");
				if (firstFlag) {
					if (col.isNullable()) {
						parts.append("AND ");
					} else {
						parts.append("    ");
					}
					firstFlag = false;
				} else {
					parts.append("AND ");
				}
				parts.append(col.getColumnIdentifier()).append(" = ").append("/*").append(col.getCamelColumnName())
						.append("*/''").append(System.lineSeparator());
				if (col.isNullable()) {
					wrapIfComment(sql, parts, col);
				} else {
					sql.append(parts);
				}
			}
		}
		return sql.toString();
	}
837082
private EntityMetadata build(Class<V> clazz) throws MetadataException {
        return EntityMetadata.buildEntityMetadata(clazz, getCassandraClient());
    }
335281
private void onQuery(EntityMetadata m, Client client)
    {

        try
        {
            // Called only in case of standalone entity.
            FilterList filter = null;
            if (translator.getFilter() != null)
            {
                filter = new FilterList(translator.getFilter());
            }
            String[] columnAsArr = getColumnsAsArray();

            if (isFindKeyOnly(m, columnAsArr))
            {
                this.handler.setFilter(new KeyOnlyFilter());
            }

            if (filter == null && columns != null)
            {
                handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, translator.getStartRow(),
                        translator.getEndRow(), columnAsArr, null);
            }
            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
            {
                if (filter == null)
                {
                    // means complete scan without where clause, scan all
                    // records.
                    // findAll.
                    if (translator.isRangeScan())
                    {
                        handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, translator.getStartRow(),
                                translator.getEndRow(), columnAsArr, null);
                    }
                    else
                    {
                        handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, null, null, columnAsArr, null);
                    }
                }
                else
                {
                    // means WHERE clause is present.
                    if (translator.isRangeScan())
                    {
                        handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, translator.getStartRow(),
                                translator.getEndRow(), columnAsArr, filter);
                    }
                    else
                    {
                        // if range query. means query over id column. create
                        // range
                        // scan method.

                        handler.readData(m.getSchema(), entityMetadata.getEntityClazz(), entityMetadata, null,
                                m.getRelationNames(), filter, columnAsArr);
                    }
                }
            }
        }
        catch (IOException ioex)
        {
            log.error("Error while executing query{} , Caused by:", ioex);
            throw new QueryHandlerException("Error while executing , Caused by:", ioex);
        }
    }
983713
private void onCompositeColumns(CQLTranslator translator, List<ColumnInfo> compositeColumns,
            StringBuilder queryBuilder, List<ColumnInfo> columns, boolean isCounterColumnFamily)
    {
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                puMetadata.getPersistenceUnitName());
        for (ColumnInfo colInfo : compositeColumns)
        {
            if (columns == null || (columns != null && !columns.contains(colInfo)))
            {
                String cqlType = null;
                if (isCounterColumnFamily)
                {
                    cqlType = "counter";
                    translator.appendColumnName(queryBuilder, colInfo.getColumnName(), cqlType);
                    queryBuilder.append(Constants.SPACE_COMMA);
                }
                // check for composite partition keys #734
                else if (colInfo.getType().isAnnotationPresent(Embeddable.class))
                {
                    EmbeddableType embeddedObject = (EmbeddableType) metaModel.embeddable(colInfo.getType());
                    for (Field embeddedColumn : colInfo.getType().getDeclaredFields())
                    {
                        if (!ReflectUtils.isTransientOrStatic(embeddedColumn))
                        {
                            validateAndAppendColumnName(translator, queryBuilder,
                                    ((AbstractAttribute) embeddedObject.getAttribute(embeddedColumn.getName()))
                                            .getJPAColumnName(), embeddedColumn.getType());
                        }
                    }

                }
                else
                {
                    validateAndAppendColumnName(translator, queryBuilder, colInfo.getColumnName(), colInfo.getType());
                }

            }
        }
    }
636960
public static MetamodelImpl getMetamodel(final KunderaMetadata kunderaMetadata, String... persistenceUnits)
    {
        MetamodelImpl metamodel = null;
        for (String pu : persistenceUnits)
        {
            metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(pu);

            if (metamodel != null)
            {
                return metamodel;
            }
        }

        // FIXME: I need to verify this why we need common entity metadata now!
        // if (metamodel == null)
        // {
        // metamodel = (MetamodelImpl)
        // kunderaMetadata.getApplicationMetadata().getMetamodel(
        // Constants.COMMON_ENTITY_METADATAS);
        // }
        return metamodel;
    }
336825
public static boolean containsBasicElementCollectionField(final EntityMetadata m,
            final KunderaMetadata kunderaMetadata)
    {
        Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());
        EntityType entityType = metaModel.entity(m.getEntityClazz());
        Iterator<Attribute> iter = entityType.getAttributes().iterator();
        while (iter.hasNext())
        {
            Attribute attr = iter.next();

            if (attr.isCollection() && !attr.isAssociation()
                    && isBasicElementCollectionField((Field) attr.getJavaMember()))
            {
                return true;
            }
        }
        return false;
    }
927743
public Query getQueryImplementation(String jpaQuery, PersistenceDelegator persistenceDelegator, Class mappedClass,
            boolean isNative, final KunderaMetadata kunderaMetadata)
    {
        if (jpaQuery == null)
        {
            throw new QueryHandlerException("Query String should not be null ");
        }

        if (jpaQuery.trim().endsWith(Constants.SEMI_COLON))
        {
            throw new QueryHandlerException("unexpected char: ';' in query [ " + jpaQuery + " ]");
        }

        KunderaQuery kunderaQuery = null;
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
        String mappedQuery = appMetadata.getQuery(jpaQuery);

        isNative = mappedQuery != null ? appMetadata.isNative(jpaQuery) : isNative;

        EntityMetadata m = null;

        // In case of named native query
        if (!isNative)
        {
            kunderaQuery = new KunderaQuery(mappedQuery != null ? mappedQuery : jpaQuery, kunderaMetadata);
            KunderaQueryParser parser = new KunderaQueryParser(kunderaQuery);

            parser.parse();

            kunderaQuery.postParsingInit();
            m = kunderaQuery.getEntityMetadata();
        }
        else
        {
            // Means if it is a namedNativeQuery.
            if (appMetadata.isNative(jpaQuery))
            {
                mappedClass = appMetadata.getMappedClass(jpaQuery);
            }

            kunderaQuery = new KunderaQuery(jpaQuery, kunderaMetadata);

            kunderaQuery.isNativeQuery = true;

            m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, mappedClass);

            Field entityClazzField = null;
            try
            {
                entityClazzField = kunderaQuery.getClass().getDeclaredField("entityClass");
                if (entityClazzField != null && !entityClazzField.isAccessible())
                {
                    entityClazzField.setAccessible(true);
                }

                entityClazzField.set(kunderaQuery, mappedClass);
            }
            catch (Exception e)
            {
                log.error(e.getMessage());
                throw new QueryHandlerException(e);
            }
        }

        Query query = null;

        try
        {
            query = getQuery(jpaQuery, persistenceDelegator, m, kunderaQuery, kunderaMetadata);
        }
        catch (Exception e)
        {
            log.error(e.getMessage());
            throw new QueryHandlerException(e);
        }
        return query;
    }
412400
private void addPredicatesToScannerBuilder(KuduScannerBuilder scannerBuilder, EmbeddableType embeddable,
            Field[] fields, MetamodelImpl metaModel, Object key)
    {
        for (Field f : fields)
        {
            if (!ReflectUtils.isTransientOrStatic(f))
            {
                Object value = PropertyAccessorHelper.getObject(key, f);
                if (f.getType().isAnnotationPresent(Embeddable.class))
                {
                    // nested
                    addPredicatesToScannerBuilder(scannerBuilder, (EmbeddableType) metaModel.embeddable(f.getType()),
                            f.getType().getDeclaredFields(), metaModel, value);
                }
                else
                {

                    Attribute attribute = embeddable.getAttribute(f.getName());
                    Type type = KuduDBValidationClassMapper.getValidTypeForClass(f.getType());
                    ColumnSchema column = new ColumnSchema.ColumnSchemaBuilder(
                            ((AbstractAttribute) attribute).getJPAColumnName(), type).build();
                    KuduPredicate predicate = KuduDBDataHandler.getEqualComparisonPredicate(column, type, value);
                    scannerBuilder.addPredicate(predicate);
                }
            }
        }

    }