Java Code Examples for org.apache.cassandra.transport.messages.ResultMessage#Rows

The following examples show how to use org.apache.cassandra.transport.messages.ResultMessage#Rows . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSTableAttachedSecondaryIndexTest.java    From sasi with Apache License 2.0 6 votes vote down vote up
private Set<String> executeCQL(String rawStatement) throws Exception
{
    SelectStatement statement = (SelectStatement) QueryProcessor.parseStatement(rawStatement).prepare().statement;
    ResultMessage.Rows cqlRows = statement.executeInternal(QueryState.forInternalCalls(), new QueryOptions(ConsistencyLevel.LOCAL_ONE, Collections.<ByteBuffer>emptyList()));

    Set<String> results = new TreeSet<>();
    for (CqlRow row : cqlRows.toThriftResult().getRows())
    {
        for (org.apache.cassandra.thrift.Column col : row.columns)
        {
            String columnName = UTF8Type.instance.getString(col.bufferForName());
            if (columnName.equals("key"))
                results.add(AsciiType.instance.getString(col.bufferForValue()));
        }
    }

    return results;
}
 
Example 2
Source File: ModificationStatement.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public ResultMessage executeWithCondition(QueryState queryState, QueryOptions options)
throws RequestExecutionException, RequestValidationException
{
    List<ByteBuffer> keys = buildPartitionKeyNames(options);
    // We don't support IN for CAS operation so far
    if (keys.size() > 1)
        throw new InvalidRequestException("IN on the partition key is not supported with conditional updates");

    ByteBuffer key = keys.get(0);
    long now = options.getTimestamp(queryState);
    Composite prefix = createClusteringPrefix(options);

    CQL3CasRequest request = new CQL3CasRequest(cfm, key, false);
    addConditions(prefix, request, options);
    request.addRowUpdate(prefix, this, options, now);

    ColumnFamily result = StorageProxy.cas(keyspace(),
                                           columnFamily(),
                                           key,
                                           request,
                                           options.getSerialConsistency(),
                                           options.getConsistency(),
                                           queryState.getClientState());
    return new ResultMessage.Rows(buildCasResultSet(key, result, options));
}
 
Example 3
Source File: SelectStatement.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private ResultMessage.Rows execute(Pageable command, QueryOptions options, int limit, long now, QueryState state) throws RequestValidationException, RequestExecutionException
{
    List<Row> rows;
    if (command == null)
    {
        rows = Collections.<Row>emptyList();
    }
    else
    {
        rows = command instanceof Pageable.ReadCommands
             ? StorageProxy.read(((Pageable.ReadCommands)command).commands, options.getConsistency(), state.getClientState())
             : StorageProxy.getRangeSlice((RangeSliceCommand)command, options.getConsistency());
    }

    return processResults(rows, options, limit, now);
}
 
Example 4
Source File: SelectStatement.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private ResultMessage.Rows pageCountQuery(QueryPager pager, QueryOptions options, int pageSize, long now, int limit) throws RequestValidationException, RequestExecutionException
{
    int count = 0;
    while (!pager.isExhausted())
    {
        int maxLimit = pager.maxRemaining();
        logger.debug("New maxLimit for paged count query is {}", maxLimit);
        ResultSet rset = process(pager.fetchPage(pageSize), options, maxLimit, now);
        count += rset.rows.size();
    }

    // We sometimes query one more result than the user limit asks to handle exclusive bounds with compact tables (see updateLimitForQuery).
    // So do make sure the count is not greater than what the user asked for.
    ResultSet result = ResultSet.makeCountResult(keyspace(), columnFamily(), Math.min(count, limit), parameters.countAlias);
    return new ResultMessage.Rows(result);
}
 
Example 5
Source File: CqlOperation.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
@Override
public Function<ResultMessage, ByteBuffer[][]> thriftHandler()
{
    return new Function<ResultMessage, ByteBuffer[][]>()
    {

        @Override
        public ByteBuffer[][] apply(ResultMessage result)
        {
            if (!(result instanceof ResultMessage.Rows))
                return new ByteBuffer[0][];

            ResultMessage.Rows rows = ((ResultMessage.Rows) result);
            ByteBuffer[][] r = new ByteBuffer[rows.result.size()][];
            for (int i = 0 ; i < r.length ; i++)
            {
                List<ByteBuffer> row = rows.result.rows.get(i);
                r[i] = new ByteBuffer[row.size()];
                for (int j = 0 ; j < row.size() ; j++)
                    r[i][j] = row.get(j);
            }
            return r;
        }
    };
}
 
Example 6
Source File: CqlOperation.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
@Override
public Function<ResultMessage, byte[][]> thriftHandler()
{
    return new Function<ResultMessage, byte[][]>()
    {

        @Override
        public byte[][] apply(ResultMessage result)
        {
            if (result instanceof ResultMessage.Rows)
            {
                ResultMessage.Rows rows = ((ResultMessage.Rows) result);
                byte[][] r = new byte[rows.result.size()][];
                for (int i = 0 ; i < r.length ; i++)
                    r[i] = rows.result.rows.get(i).get(0).array();
                return r;
            }
            return null;
        }
    };
}
 
Example 7
Source File: QueryProcessor.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static UntypedResultSet process(String query, ConsistencyLevel cl) throws RequestExecutionException
{
    try
    {
        ResultMessage result = instance.process(query, QueryState.forInternalCalls(), QueryOptions.forInternalCalls(cl, Collections.<ByteBuffer>emptyList()));
        if (result instanceof ResultMessage.Rows)
            return UntypedResultSet.create(((ResultMessage.Rows)result).result);
        else
            return null;
    }
    catch (RequestValidationException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: ListPermissionsStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private ResultMessage resultMessage(List<PermissionDetails> details)
{
    if (details.isEmpty())
        return new ResultMessage.Void();

    ResultSet result = new ResultSet(metadata);
    for (PermissionDetails pd : details)
    {
        result.addColumnValue(UTF8Type.instance.decompose(pd.username));
        result.addColumnValue(UTF8Type.instance.decompose(pd.resource.toString()));
        result.addColumnValue(UTF8Type.instance.decompose(pd.permission.toString()));
    }
    return new ResultMessage.Rows(result);
}
 
Example 9
Source File: SelectStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage.Rows processResults(List<Row> rows, QueryOptions options, int limit, long now) throws RequestValidationException
{
    // Even for count, we need to process the result as it'll group some column together in sparse column families
    ResultSet rset = process(rows, options, limit, now);
    rset = parameters.isCount ? rset.makeCountResult(parameters.countAlias) : rset;
    return new ResultMessage.Rows(rset);
}
 
Example 10
Source File: SelectStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage.Rows executeInternal(QueryState state, QueryOptions options) throws RequestExecutionException, RequestValidationException
{
    int limit = getLimit(options);
    long now = System.currentTimeMillis();
    Pageable command = getPageableCommand(options, limit, now);
    List<Row> rows = command == null
                   ? Collections.<Row>emptyList()
                   : (command instanceof Pageable.ReadCommands
                      ? readLocally(keyspace(), ((Pageable.ReadCommands)command).commands)
                      : ((RangeSliceCommand)command).executeLocally());

    return processResults(rows, options, limit, now);
}
 
Example 11
Source File: CqlOperation.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
@Override
public Function<ResultMessage, Integer> thriftHandler()
{
    return new Function<ResultMessage, Integer>()
    {
        @Override
        public Integer apply(ResultMessage result)
        {
            return result instanceof ResultMessage.Rows ? ((ResultMessage.Rows) result).result.size() : 0;
        }
    };
}
 
Example 12
Source File: BatchStatement.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
private ResultMessage executeWithConditions(BatchQueryOptions options, QueryState state)
throws RequestExecutionException, RequestValidationException
{
    long now = state.getTimestamp();
    ByteBuffer key = null;
    String ksName = null;
    String cfName = null;
    CQL3CasRequest casRequest = null;
    Set<ColumnDefinition> columnsWithConditions = new LinkedHashSet<>();

    for (int i = 0; i < statements.size(); i++)
    {
        ModificationStatement statement = statements.get(i);
        QueryOptions statementOptions = options.forStatement(i);
        long timestamp = attrs.getTimestamp(now, statementOptions);
        List<ByteBuffer> pks = statement.buildPartitionKeyNames(statementOptions);
        if (pks.size() > 1)
            throw new IllegalArgumentException("Batch with conditions cannot span multiple partitions (you cannot use IN on the partition key)");
        if (key == null)
        {
            key = pks.get(0);
            ksName = statement.cfm.ksName;
            cfName = statement.cfm.cfName;
            casRequest = new CQL3CasRequest(statement.cfm, key, true);
        }
        else if (!key.equals(pks.get(0)))
        {
            throw new InvalidRequestException("Batch with conditions cannot span multiple partitions");
        }

        Composite clusteringPrefix = statement.createClusteringPrefix(statementOptions);
        if (statement.hasConditions())
        {
            statement.addConditions(clusteringPrefix, casRequest, statementOptions);
            // As soon as we have a ifNotExists, we set columnsWithConditions to null so that everything is in the resultSet
            if (statement.hasIfNotExistCondition() || statement.hasIfExistCondition())
                columnsWithConditions = null;
            else if (columnsWithConditions != null)
                Iterables.addAll(columnsWithConditions, statement.getColumnsWithConditions());
        }
        casRequest.addRowUpdate(clusteringPrefix, statement, statementOptions, timestamp);
    }

    ColumnFamily result = StorageProxy.cas(ksName, cfName, key, casRequest, options.getSerialConsistency(), options.getConsistency(), state.getClientState());

    return new ResultMessage.Rows(ModificationStatement.buildCasResultSet(ksName, key, cfName, result, columnsWithConditions, true, options.forStatement(0)));
}
 
Example 13
Source File: SelectStatement.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public ResultMessage.Rows execute(QueryState state, QueryOptions options) throws RequestExecutionException, RequestValidationException
{
    ConsistencyLevel cl = options.getConsistency();
    if (cl == null)
        throw new InvalidRequestException("Invalid empty consistency level");

    cl.validateForRead(keyspace());

    int limit = getLimit(options);
    long now = System.currentTimeMillis();
    Pageable command = getPageableCommand(options, limit, now);

    int pageSize = options.getPageSize();
    // A count query will never be paged for the user, but we always page it internally to avoid OOM.
    // If we user provided a pageSize we'll use that to page internally (because why not), otherwise we use our default
    // Note that if there are some nodes in the cluster with a version less than 2.0, we can't use paging (CASSANDRA-6707).
    if (parameters.isCount && pageSize <= 0)
        pageSize = DEFAULT_COUNT_PAGE_SIZE;

    if (pageSize <= 0 || command == null || !QueryPagers.mayNeedPaging(command, pageSize))
    {
        return execute(command, options, limit, now, state);
    }
    else
    {
        QueryPager pager = QueryPagers.pager(command, cl, state.getClientState(), options.getPagingState());
        if (parameters.isCount)
            return pageCountQuery(pager, options, pageSize, now, limit);

        // We can't properly do post-query ordering if we page (see #6722)
        if (needsPostQueryOrdering())
            throw new InvalidRequestException("Cannot page queries with both ORDER BY and a IN restriction on the partition key; you must either remove the "
                                            + "ORDER BY or the IN and sort client side, or disable paging for this query");

        List<Row> page = pager.fetchPage(pageSize);
        ResultMessage.Rows msg = processResults(page, options, limit, now);

        if (!pager.isExhausted())
            msg.result.metadata.setHasMorePages(pager.state());

        return msg;
    }
}