org.apache.cassandra.transport.messages.ResultMessage Java Examples

The following examples show how to use org.apache.cassandra.transport.messages.ResultMessage. 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: 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 #2
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 #3
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 #4
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 #5
Source File: ListPermissionsStatement.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public ResultMessage execute(ClientState state) throws RequestValidationException, RequestExecutionException
{
    List<PermissionDetails> details = new ArrayList<PermissionDetails>();

    if (resource != null && recursive)
    {
        for (IResource r : Resources.chain(resource))
            details.addAll(list(state, r));
    }
    else
    {
        details.addAll(list(state, resource));
    }

    Collections.sort(details);
    return resultMessage(details);
}
 
Example #6
Source File: QueryProcessor.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public ResultMessage processPrepared(CQLStatement statement, QueryState queryState, QueryOptions options)
throws RequestExecutionException, RequestValidationException
{
    List<ByteBuffer> variables = options.getValues();
    // Check to see if there are any bound variables to verify
    if (!(variables.isEmpty() && (statement.getBoundTerms() == 0)))
    {
        if (variables.size() != statement.getBoundTerms())
            throw new InvalidRequestException(String.format("there were %d markers(?) in CQL but %d bound variables",
                                                            statement.getBoundTerms(),
                                                            variables.size()));

        // at this point there is a match in count between markers and variables that is non-zero

        if (logger.isTraceEnabled())
            for (int i = 0; i < variables.size(); i++)
                logger.trace("[{}] '{}'", i+1, variables.get(i));
    }

    metrics.preparedStatementsExecuted.inc();
    return processStatement(statement, queryState, options);
}
 
Example #7
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 #8
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 #9
Source File: BatchStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private ResultMessage execute(QueryState queryState, BatchQueryOptions options, boolean local, long now)
throws RequestExecutionException, RequestValidationException
{
    if (options.getConsistency() == null)
        throw new InvalidRequestException("Invalid empty consistency level");
    if (options.getSerialConsistency() == null)
        throw new InvalidRequestException("Invalid empty serial consistency level");

    if (hasConditions)
        return executeWithConditions(options, queryState);

    executeWithoutConditions(getMutations(options, local, now), options.getConsistency());
    return new ResultMessage.Void();
}
 
Example #10
Source File: BatchStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage executeInternal(QueryState queryState, QueryOptions options) throws RequestValidationException, RequestExecutionException
{
    assert !hasConditions;
    for (IMutation mutation : getMutations(BatchQueryOptions.withoutPerStatementVariables(options), true, queryState.getTimestamp()))
    {
        // We don't use counters internally.
        assert mutation instanceof Mutation;
        ((Mutation) mutation).apply();
    }
    return null;
}
 
Example #11
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 #12
Source File: DropUserStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage execute(ClientState state) throws RequestValidationException, RequestExecutionException
{
    // not rejected in validate()
    if (ifExists && !Auth.isExistingUser(username))
        return null;

    // clean up permissions after the dropped user.
    DatabaseDescriptor.getAuthorizer().revokeAll(username);
    Auth.deleteUser(username);
    DatabaseDescriptor.getAuthenticator().drop(username);
    return null;
}
 
Example #13
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 #14
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 #15
Source File: CreateUserStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage execute(ClientState state) throws RequestValidationException, RequestExecutionException
{
    // not rejected in validate()
    if (ifNotExists && Auth.isExistingUser(username))
        return null;

    DatabaseDescriptor.getAuthenticator().create(username, opts.getOptions());
    Auth.insertUser(username, superuser);
    return null;
}
 
Example #16
Source File: SchemaAlteringStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage execute(QueryState state, QueryOptions options) throws RequestValidationException
{
    // If an IF [NOT] EXISTS clause was used, this may not result in an actual schema change.  To avoid doing
    // extra work in the drivers to handle schema changes, we return an empty message in this case. (CASSANDRA-7600)
    boolean didChangeSchema = announceMigration(false);
    return didChangeSchema ? new ResultMessage.SchemaChange(changeEvent()) : new ResultMessage.Void();
}
 
Example #17
Source File: SchemaAlteringStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage executeInternal(QueryState state, QueryOptions options)
{
    try
    {
        boolean didChangeSchema = announceMigration(true);
        return didChangeSchema ? new ResultMessage.SchemaChange(changeEvent()) : new ResultMessage.Void();
    }
    catch (RequestValidationException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #18
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 #19
Source File: QueryProcessor.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage processStatement(CQLStatement statement, QueryState queryState, QueryOptions options)
throws RequestExecutionException, RequestValidationException
{
    logger.trace("Process {} @CL.{}", statement, options.getConsistency());
    ClientState clientState = queryState.getClientState();
    statement.checkAccess(clientState);
    statement.validate(clientState);

    ResultMessage result = statement.execute(queryState, options);
    return result == null ? new ResultMessage.Void() : result;
}
 
Example #20
Source File: QueryProcessor.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage process(String queryString, QueryState queryState, QueryOptions options)
throws RequestExecutionException, RequestValidationException
{
    ParsedStatement.Prepared p = getStatement(queryString, queryState.getClientState());
    options.prepare(p.boundNames);
    CQLStatement prepared = p.statement;
    if (prepared.getBoundTerms() != options.getValues().size())
        throw new InvalidRequestException("Invalid amount of bind variables");

    if (!queryState.getClientState().isInternal)
        metrics.regularStatementsExecuted.inc();

    return processStatement(prepared, queryState, options);
}
 
Example #21
Source File: AlterUserStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage execute(ClientState state) throws RequestValidationException, RequestExecutionException
{
    if (!opts.isEmpty())
        DatabaseDescriptor.getAuthenticator().alter(username, opts.getOptions());
    if (superuser != null)
        Auth.insertUser(username, superuser.booleanValue());
    return null;
}
 
Example #22
Source File: QueryProcessor.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage processBatch(BatchStatement batch, QueryState queryState, BatchQueryOptions options)
throws RequestExecutionException, RequestValidationException
{
    ClientState clientState = queryState.getClientState();
    batch.checkAccess(clientState);
    batch.validate();
    batch.validate(clientState);
    return batch.execute(queryState, options);
}
 
Example #23
Source File: QueryProcessor.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static ResultMessage.Prepared prepare(String queryString, ClientState clientState, boolean forThrift)
throws RequestValidationException
{
    ResultMessage.Prepared existing = getStoredPreparedStatement(queryString, clientState.getRawKeyspace(), forThrift);
    if (existing != null)
        return existing;

    ParsedStatement.Prepared prepared = getStatement(queryString, clientState);
    int boundTerms = prepared.statement.getBoundTerms();
    if (boundTerms > FBUtilities.MAX_UNSIGNED_SHORT)
        throw new InvalidRequestException(String.format("Too many markers(?). %d markers exceed the allowed maximum of %d", boundTerms, FBUtilities.MAX_UNSIGNED_SHORT));
    assert boundTerms == prepared.boundNames.size();

    return storePreparedStatement(queryString, clientState.getRawKeyspace(), prepared, forThrift);
}
 
Example #24
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 #25
Source File: ModificationStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage execute(QueryState queryState, QueryOptions options)
throws RequestExecutionException, RequestValidationException
{
    if (options.getConsistency() == null)
        throw new InvalidRequestException("Invalid empty consistency level");

    if (hasConditions() && options.getProtocolVersion() == 1)
        throw new InvalidRequestException("Conditional updates are not supported by the protocol version in use. You need to upgrade to a driver using the native protocol v2.");

    return hasConditions()
         ? executeWithCondition(queryState, options)
         : executeWithoutCondition(queryState, options);
}
 
Example #26
Source File: ModificationStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public ResultMessage executeInternal(QueryState queryState, QueryOptions options) throws RequestValidationException, RequestExecutionException
{
    if (hasConditions())
        throw new UnsupportedOperationException();

    for (IMutation mutation : getMutations(options, true, queryState.getTimestamp()))
    {
        // We don't use counters internally.
        assert mutation instanceof Mutation;

        ((Mutation) mutation).apply();
    }
    return null;
}
 
Example #27
Source File: ModificationStatement.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private ResultMessage executeWithoutCondition(QueryState queryState, QueryOptions options)
throws RequestExecutionException, RequestValidationException
{
    ConsistencyLevel cl = options.getConsistency();
    if (isCounter())
        cl.validateCounterForWrite(cfm);
    else
        cl.validateForWrite(cfm.ksName);

    Collection<? extends IMutation> mutations = getMutations(options, false, options.getTimestamp(queryState));
    if (!mutations.isEmpty())
        StorageProxy.mutateWithTriggers(mutations, cl, false);

    return null;
}
 
Example #28
Source File: UseStatement.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public ResultMessage execute(QueryState state, QueryOptions options) throws InvalidRequestException
{
    state.getClientState().setKeyspace(keyspace);
    return new ResultMessage.SetKeyspace(keyspace);
}
 
Example #29
Source File: UseStatement.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public ResultMessage executeInternal(QueryState state, QueryOptions options) throws InvalidRequestException
{
    // In production, internal queries are exclusively on the system keyspace and 'use' is thus useless
    // but for some unit tests we need to set the keyspace (e.g. for tests with DROP INDEX)
    return execute(state, options);
}
 
Example #30
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;
    }
}