On query over composite columns.

@param m
the m
@param client
the client
@param metaModel
the meta model
@param relations
the relations
@return the list
552773
public String onQueryOverCQL3(EntityMetadata m, Client client, MetamodelImpl metaModel, List<String> relations) {
        // select column will always be of entity field only!
        // where clause ordering

        Class compoundKeyClass = m.getIdAttribute().getBindableJavaType();
        EmbeddableType compoundKey = null;
        String idColumn;
        if (metaModel.isEmbeddable(compoundKeyClass)) {
            compoundKey = metaModel.embeddable(compoundKeyClass);
            idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();
        } else {
            idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();
        }
        StringBuilder builder = new StringBuilder();

        boolean isPresent = false;
        List<String> columns = getColumnList(m, metaModel, getKunderaQuery().getResult(), compoundKey);
        String selectQuery = setSelectQuery(columns);

        CQLTranslator translator = new CQLTranslator();

        selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,
            translator.ensureCase(new StringBuilder(), m.getTableName(), false).toString());

        builder = CassandraUtilities.appendColumns(builder, columns, selectQuery, translator);

        addWhereClause(builder);

        onCondition(m, metaModel, compoundKey, idColumn, builder, isPresent, translator, true);

        return builder.toString();
    }
232578
def get_m2m_value(session, request, obj):
    
    params = {}
    ''' m2m_request:

        {u'company[]': [u'["id", 1]'],
         u'professions[]': [u'["id", 2]', u'["id", 3]']}
    '''
    m2m_request = {k: v for k, v in list(request.items()) if k.endswith('[]')}
    for k, v in list(m2m_request.items()):
        key = k[:-2]
        relation = getattr(obj.__class__, key, False)
        if not relation:
            relation = getattr(obj, key, False)
        if not relation:
            continue  # pragma: no cover
        value = get_m2m_objs(session, relation, v)
        if value is None:
            continue

        if relation.property.uselist is False:
            if value:
                value = value[0]
            else:
                value = None
        params[key] = value
    return params
1011803
public List<Relation> getRelations(Collection<Long> relationIds)
	{
		if(relationIds.isEmpty()) return Collections.emptyList();
		return getSomeElements(RELATION + "s?" + RELATION + "s=" + toCommaList(relationIds), Relation.class);
	}
1365509
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        ClientMetadata clientMetadata = ((ClientBase) client).getClientMetadata();
        this.useLuceneOrES = !MetadataUtils.useSecondryIndex(clientMetadata);
        if (useLuceneOrES)
        {
            return populateUsingLucene(m, client, null, kunderaQuery.getResult());
        }
        else
        {
            CouchDBQueryInterpreter interpreter = onTranslation(getKunderaQuery().getFilterClauseQueue(), m);
            return ((CouchDBClient) client).createAndExecuteQuery(interpreter);
        }
    }
567374
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        List results = new ArrayList();

        if (!MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
        {
            results.addAll(populateUsingLucene(m, client, null, getKunderaQuery().getResult()));
        }

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

            KuduClient kuduClient = ((KuduDBClient) client).getKuduClient();
            KuduTable table;
            try
            {
                table = kuduClient.openTable(m.getTableName());
            }
            catch (Exception e)
            {
                logger.error("Cannot open table : " + m.getTableName(), e);
                throw new KunderaException("Cannot open table : " + m.getTableName(), e);
            }

            KuduScannerBuilder scannerBuilder = kuduClient.newScannerBuilder(table);
            JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();
            List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);
            if (!selectColumns.isEmpty())
            {
                // select by specific columns, set projection
                scannerBuilder.setProjectedColumnNames(selectColumns);
            }
            if (KunderaQueryUtils.hasWhereClause(jpqlExp))
            {
                // add predicate filters
                WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);
                Expression whereExp = whereClause.getConditionalExpression();
                parseAndBuildFilters(entityType, scannerBuilder, whereExp);
            }

            KuduScanner scanner = scannerBuilder.build();

            Object entity;
            while (scanner.hasMoreRows())
            {
                RowResultIterator rowResultIter;
                try
                {
                    rowResultIter = scanner.nextRows();
                }
                catch (Exception e)
                {
                    logger.error("Cannot get results from table : " + m.getTableName(), e);
                    throw new KunderaException("Cannot get results from table : " + m.getTableName(), e);
                }

                while (rowResultIter.hasNext())
                {
                    RowResult result = rowResultIter.next();
                    entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());
                    // populate RowResult to entity object and return
                    ((KuduDBClient) client).populateEntity(entity, result, entityType, metaModel);
                    results.add(entity);
                    logger.debug(result.rowToString());
                }
            }
        }
        return results;
    }
394626
protected void computeEntityViaSuperColumns(EntityMetadata m, boolean isRelation, List<String> relations,
        List<Object> entities, Map<ByteBuffer, List<SuperColumn>> qResults) {
        for (ByteBuffer key : qResults.keySet()) {
            onSuperColumn(m, isRelation, relations, entities, qResults.get(key), key);
        }
    }
755739
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        return onQuery(m, client);
    }
50624
public static function queryModelRelations($model, ...$names)
    {
        $relations = AnnotationManager::getPropertiesAnnotations(BeanFactory::getObjectClass($model), RelationBase::class);
        foreach($names as $name)
        {
            if(isset($relations[$name]))
            {
                Query::init($model, $name, $relations[$name][0], true);
            }
        }
    }
677401
@SuppressWarnings("unused") // called through reflection by RequestServer
  public ModelBuildersV3 list(int version, ModelBuildersV3 m) {
    m.model_builders = new ModelBuilderSchema.IcedHashMapStringModelBuilderSchema();
    for( String algo : ModelBuilder.algos() ) {
      ModelBuilder builder = ModelBuilder.make(algo, null, null);
      m.model_builders.put(algo.toLowerCase(), (ModelBuilderSchema)SchemaServer.schema(version, builder).fillFromImpl(builder));
    }
    return m;
  }
1119720
@Override
    protected List findUsingLucene(EntityMetadata m, Client client)
    {
        try
        {
            BasicDBObject orderByClause = getOrderByClause(m);
            // find on id, so no need to add skip() [firstResult hardcoded 0]
            return ((MongoDBClient) client).loadData(m, createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()),
                    null, orderByClause, isSingleResult ? 1 : maxResult, 0, isCountQuery(),
                    getKeys(m, getKunderaQuery().getResult()), getKunderaQuery().getResult());
        }
        catch (Exception e)
        {
            log.error("Error during executing query, Caused by:", e);
            throw new QueryHandlerException(e);
        }

    }
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);
        }
    }
46840
protected List<Object> onCounterColumn(EntityMetadata m, boolean isRelation, List<String> relations,
        List<KeySlice> ks) {
        List<Object> entities;

        if (m.getType().isSuperColumnFamilyMetadata()) {
            if (log.isInfoEnabled()) {
                log.info("On counter column for super column family of entity {}.", m.getEntityClazz());
            }

            // TODO:: change it. remove column or super column helper
            Map<byte[], List<CounterSuperColumn>> results = new HashMap<byte[], List<CounterSuperColumn>>();

            List<CounterSuperColumn> counterColumns = null;
            for (KeySlice slice : ks) {
                counterColumns = new ArrayList<CounterSuperColumn>(slice.getColumnsSize());
                for (ColumnOrSuperColumn column : slice.columns) {
                    counterColumns.add(column.counter_super_column);
                }

                results.put(slice.getKey(), counterColumns);
            }

            entities = new ArrayList<Object>(results.size());

            for (byte[] key : results.keySet()) {
                Object e = null;
                Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key);
                List<CounterSuperColumn> counterSuperColumns = results.get(key);
                ThriftRow tr = new ThriftRow(id, m.getTableName(), new ArrayList<Column>(0),
                    new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0), counterSuperColumns);
                e = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isRelation);
                entities.add(e);
            }
        } else {
            if (log.isInfoEnabled()) {
                log.info("On counter column for column family of entity {}", m.getEntityClazz());
            }

            Map<byte[], List<CounterColumn>> results = new HashMap<byte[], List<CounterColumn>>();

            List<CounterColumn> counterColumns = null;

            for (KeySlice slice : ks) {
                counterColumns = new ArrayList<CounterColumn>(slice.getColumnsSize());
                for (ColumnOrSuperColumn column : slice.columns) {
                    counterColumns.add(column.counter_column);
                }

                results.put(slice.getKey(), counterColumns);
            }

            entities = new ArrayList<Object>(results.size());

            for (byte[] key : results.keySet()) {
                Object e = null;
                Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key);

                List<CounterColumn> columns = results.get(key);
                ThriftRow tr = new ThriftRow(id, m.getTableName(), new ArrayList<Column>(0),
                    new ArrayList<SuperColumn>(0), columns, new ArrayList<CounterSuperColumn>(0));
                e = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isRelation);

                if (e != null) {
                    entities.add(e);
                }
            }
        }
        return entities;
    }
451793
protected List<EnhanceEntity> onAssociationUsingLucene(EntityMetadata m, Client client, List<EnhanceEntity> ls)
    {
        Set<String> rSet = fetchDataFromLucene(m.getEntityClazz(), client);
        List resultList = client.findAll(m.getEntityClazz(), null, rSet.toArray(new String[] {}));
        return m.getRelationNames() != null && !m.getRelationNames().isEmpty() ? resultList : transform(m, ls,
                resultList);
    }
41611
List<String> getColumnList(EntityMetadata m, MetamodelImpl metamodel, String[] results,
        EmbeddableType compoundKey) {
        List<String> columns = new ArrayList<String>();
        if (results != null && results.length > 0) {
            MetamodelImpl metaModel =
                (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());
            EntityType entity = metaModel.entity(m.getEntityClazz());

            String keyFieldName = CassandraUtilities.getIdColumnName(kunderaMetadata, m, externalProperties,
                ((CassandraClientBase) persistenceDelegeator.getClient(m)).isCql3Enabled(m));
            for (int i = 1; i < results.length; i++) {
                if (results[i] != null) {
                    if (results[i].indexOf(".") > 0) {
                        String fieldName = results[i].substring(0, results[i].indexOf("."));
                        String embeddedFieldName =
                            results[i].substring(results[i].indexOf(".") + 1, results[i].length());
                        AbstractAttribute attribute = (AbstractAttribute) entity.getAttribute(fieldName);
                        EmbeddableType embeddable = metamodel.embeddable(attribute.getBindableJavaType());
                        Attribute embeddableAttribute = embeddable.getAttribute(embeddedFieldName);
                        columns.add(((AbstractAttribute) embeddableAttribute).getJPAColumnName());
                    } else {
                        Attribute attribute = entity.getAttribute(results[i]);
                        if (attribute == null) {
                            throw new QueryHandlerException("Column type is null for : " + results);
                        } else if (m.getIdAttribute().equals(attribute) && compoundKey != null) {
                            Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();
                            for (Field field : fields) {
                                addCompositeIdToColumns(metamodel, compoundKey, columns, field);
                            }
                        } else if (m.getIdAttribute().equals(attribute) && compoundKey == null) {
                            columns.add(keyFieldName);
                        } else {
                            columns.add(((AbstractAttribute) attribute).getJPAColumnName());
                        }
                    }
                }
            }
            return columns;
        }

        if (log.isInfoEnabled()) {
            log.info("No record found, returning null.");
        }
        return null;
    }
1201066
@Override
    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)
    {
        // TODO Auto-generated method stub
        return null;
    }
339727
@Override
    public List findByRange(byte[] minVal, byte[] maxVal, EntityMetadata m, boolean isWrapReq, List<String> relations,
            List<String> columns, List<IndexExpression> conditions, int maxResults) throws Exception
    {
        SlicePredicate slicePredicate = new SlicePredicate();

        if (columns != null && !columns.isEmpty())
        {
            List asList = new ArrayList(32);
            for (String colName : columns)
            {
                if (colName != null)
                {
                    asList.add(UTF8Type.instance.decompose(colName));
                }
            }
            slicePredicate.setColumn_names(asList);
        }
        else
        {
            SliceRange sliceRange = new SliceRange();
            sliceRange.setStart(ByteBufferUtil.EMPTY_BYTE_BUFFER);
            sliceRange.setFinish(ByteBufferUtil.EMPTY_BYTE_BUFFER);
            slicePredicate.setSlice_range(sliceRange);
        }

        KeyRange keyRange = new KeyRange(maxResults);
        keyRange.setStart_key(minVal == null ? "".getBytes() : minVal);
        keyRange.setEnd_key(maxVal == null ? "".getBytes() : maxVal);
        ColumnParent cp = new ColumnParent(m.getTableName());

        if (conditions != null && !conditions.isEmpty())
        {
            keyRange.setRow_filter(conditions);
            keyRange.setRow_filterIsSet(true);
        }

        Connection conn = getConnection();

        List<KeySlice> keys = conn.getClient().get_range_slices(cp, slicePredicate, keyRange, getConsistencyLevel());

        releaseConnection(conn);

        List results = null;
        if (keys != null)
        {
            results = populateEntitiesFromKeySlices(m, isWrapReq, relations, keys, dataHandler);
        }
        return results;
    }
265417
@SuppressWarnings("unchecked")
    @Override
    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client) {
        List<EnhanceEntity> ls = null;
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
        externalProperties = ((CassandraClientBase) client).getExternalProperties();
        MetamodelImpl metaModel =
            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());

        String query = appMetadata.getQuery(getJPAQuery());
        boolean isNative = kunderaQuery.isNative();

        if (isNative) {
            ls = (List<EnhanceEntity>) ((CassandraClientBase) client).executeQuery(m.getEntityClazz(),
                m.getRelationNames(), isNative, query != null ? query : getJPAQuery());
        } else if (!isNative && ((CassandraClientBase) client).isCql3Enabled(m)) {
            // edited
            // check if lucene or indexer are enabled then populate
            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {
                ls = ((CassandraClientBase) client).executeQuery(m.getEntityClazz(), m.getRelationNames(), isNative,

                    onQueryOverCQL3(m, client, metaModel, m.getRelationNames()));
            } else {
                ls = populateUsingLucene(m, client, null, getKunderaQuery().getResult());
            }
        } else {
            // Index in Inverted Index table if applicable
            boolean useInvertedIndex = CassandraIndexHelper.isInvertedIndexingApplicable(m,
                MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()));
            Map<Boolean, List<IndexClause>> ixClause =
                MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())
                    ? prepareIndexClause(m, useInvertedIndex) : null;

            if (useInvertedIndex && !getKunderaQuery().getFilterClauseQueue().isEmpty()) {
                ls = ((CassandraEntityReader) getReader()).readFromIndexTable(m, client, ixClause);
            } else {
                ((CassandraEntityReader) getReader()).setConditions(ixClause);
                ls = reader.populateRelation(m, client, isSingleResult ? 1 : this.maxResult);
            }
        }
        return setRelationEntities(ls, client, m);
    }