Search in sources :

Example 6 with QueryHandler

use of org.apache.cassandra.cql3.QueryHandler in project cassandra by apache.

the class PrepareMessage method execute.

@Override
protected Message.Response execute(QueryState state, long queryStartNanoTime, boolean traceRequest) {
    try {
        if (traceRequest)
            Tracing.instance.begin("Preparing CQL3 query", state.getClientAddress(), ImmutableMap.of("query", query));
        ClientState clientState = state.getClientState().cloneWithKeyspaceIfSet(keyspace);
        QueryHandler queryHandler = ClientState.getCQLQueryHandler();
        long queryTime = currentTimeMillis();
        ResultMessage.Prepared response = queryHandler.prepare(query, clientState, getCustomPayload());
        QueryEvents.instance.notifyPrepareSuccess(() -> queryHandler.getPrepared(response.statementId), query, state, queryTime, response);
        return response;
    } catch (Exception e) {
        QueryEvents.instance.notifyPrepareFailure(null, query, state, e);
        JVMStabilityInspector.inspectThrowable(e);
        return ErrorMessage.fromException(e);
    }
}
Also used : ClientState(org.apache.cassandra.service.ClientState) QueryHandler(org.apache.cassandra.cql3.QueryHandler)

Example 7 with QueryHandler

use of org.apache.cassandra.cql3.QueryHandler in project cassandra by apache.

the class BatchMessage method execute.

@Override
protected Message.Response execute(QueryState state, long queryStartNanoTime, boolean traceRequest) {
    List<QueryHandler.Prepared> prepared = null;
    try {
        if (traceRequest)
            traceQuery(state);
        QueryHandler handler = ClientState.getCQLQueryHandler();
        prepared = new ArrayList<>(queryOrIdList.size());
        for (int i = 0; i < queryOrIdList.size(); i++) {
            Object query = queryOrIdList.get(i);
            QueryHandler.Prepared p;
            if (query instanceof String) {
                p = QueryProcessor.parseAndPrepare((String) query, state.getClientState().cloneWithKeyspaceIfSet(options.getKeyspace()), false);
            } else {
                p = handler.getPrepared((MD5Digest) query);
                if (null == p)
                    throw new PreparedQueryNotFoundException((MD5Digest) query);
            }
            List<ByteBuffer> queryValues = values.get(i);
            if (queryValues.size() != p.statement.getBindVariables().size())
                throw new InvalidRequestException(String.format("There were %d markers(?) in CQL but %d bound variables", p.statement.getBindVariables().size(), queryValues.size()));
            prepared.add(p);
        }
        BatchQueryOptions batchOptions = BatchQueryOptions.withPerStatementVariables(options, values, queryOrIdList);
        List<ModificationStatement> statements = new ArrayList<>(prepared.size());
        List<String> queries = QueryEvents.instance.hasListeners() ? new ArrayList<>(prepared.size()) : null;
        for (int i = 0; i < prepared.size(); i++) {
            CQLStatement statement = prepared.get(i).statement;
            if (queries != null)
                queries.add(prepared.get(i).rawCQLStatement);
            batchOptions.prepareStatement(i, statement.getBindVariables());
            if (!(statement instanceof ModificationStatement))
                throw new InvalidRequestException("Invalid statement in batch: only UPDATE, INSERT and DELETE statements are allowed.");
            statements.add((ModificationStatement) statement);
        }
        // Note: It's ok at this point to pass a bogus value for the number of bound terms in the BatchState ctor
        // (and no value would be really correct, so we prefer passing a clearly wrong one).
        BatchStatement batch = new BatchStatement(batchType, VariableSpecifications.empty(), statements, Attributes.none());
        long queryTime = currentTimeMillis();
        Message.Response response = handler.processBatch(batch, state, batchOptions, getCustomPayload(), queryStartNanoTime);
        if (queries != null)
            QueryEvents.instance.notifyBatchSuccess(batchType, statements, queries, values, options, state, queryTime, response);
        return response;
    } catch (Exception e) {
        QueryEvents.instance.notifyBatchFailure(prepared, batchType, queryOrIdList, values, options, state, e);
        JVMStabilityInspector.inspectThrowable(e);
        return ErrorMessage.fromException(e);
    }
}
Also used : CQLStatement(org.apache.cassandra.cql3.CQLStatement) QueryHandler(org.apache.cassandra.cql3.QueryHandler) Message(org.apache.cassandra.transport.Message) BatchQueryOptions(org.apache.cassandra.cql3.BatchQueryOptions) ModificationStatement(org.apache.cassandra.cql3.statements.ModificationStatement) ArrayList(java.util.ArrayList) PreparedQueryNotFoundException(org.apache.cassandra.exceptions.PreparedQueryNotFoundException) ByteBuffer(java.nio.ByteBuffer) PreparedQueryNotFoundException(org.apache.cassandra.exceptions.PreparedQueryNotFoundException) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException) ProtocolException(org.apache.cassandra.transport.ProtocolException) MD5Digest(org.apache.cassandra.utils.MD5Digest) BatchStatement(org.apache.cassandra.cql3.statements.BatchStatement) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException)

Example 8 with QueryHandler

use of org.apache.cassandra.cql3.QueryHandler in project cassandra by apache.

the class ExecuteMessage method execute.

@Override
protected Message.Response execute(QueryState state, long queryStartNanoTime, boolean traceRequest) {
    QueryHandler.Prepared prepared = null;
    try {
        QueryHandler handler = ClientState.getCQLQueryHandler();
        prepared = handler.getPrepared(statementId);
        if (prepared == null)
            throw new PreparedQueryNotFoundException(statementId);
        if (!prepared.fullyQualified && !Objects.equals(state.getClientState().getRawKeyspace(), prepared.keyspace) && // We can not reliably detect inconsistencies for batches yet
        !(prepared.statement instanceof BatchStatement)) {
            state.getClientState().warnAboutUseWithPreparedStatements(statementId, prepared.keyspace);
            String msg = String.format("Tried to execute a prepared unqalified statement on a keyspace it was not prepared on. " + " Executing the resulting prepared statement will return unexpected results: %s (on keyspace %s, previously prepared on %s)", statementId, state.getClientState().getRawKeyspace(), prepared.keyspace);
            nospam.error(msg);
        }
        CQLStatement statement = prepared.statement;
        options.prepare(statement.getBindVariables());
        if (options.getPageSize() == 0)
            throw new ProtocolException("The page size cannot be 0");
        if (traceRequest)
            traceQuery(state, prepared);
        // Some custom QueryHandlers are interested by the bound names. We provide them this information
        // by wrapping the QueryOptions.
        QueryOptions queryOptions = QueryOptions.addColumnSpecifications(options, prepared.statement.getBindVariables());
        long requestStartTime = currentTimeMillis();
        Message.Response response = handler.processPrepared(statement, state, queryOptions, getCustomPayload(), queryStartNanoTime);
        QueryEvents.instance.notifyExecuteSuccess(prepared.statement, prepared.rawCQLStatement, options, state, requestStartTime, response);
        if (response instanceof ResultMessage.Rows) {
            ResultMessage.Rows rows = (ResultMessage.Rows) response;
            ResultSet.ResultMetadata resultMetadata = rows.result.metadata;
            if (options.getProtocolVersion().isGreaterOrEqualTo(ProtocolVersion.V5)) {
                // for details.
                if (!statement.hasConditions()) {
                    // check if there was a change, comparing it with metadata that's about to be returned to client.
                    if (!resultMetadata.getResultMetadataId().equals(resultMetadataId))
                        resultMetadata.setMetadataChanged();
                    else if (options.skipMetadata())
                        resultMetadata.setSkipMetadata();
                }
            } else {
                // and compare it with the metadata to be returned to client.
                if (options.skipMetadata() && prepared.resultMetadataId.equals(resultMetadata.getResultMetadataId()))
                    resultMetadata.setSkipMetadata();
            }
        }
        return response;
    } catch (Exception e) {
        QueryEvents.instance.notifyExecuteFailure(prepared, options, state, e);
        JVMStabilityInspector.inspectThrowable(e);
        return ErrorMessage.fromException(e);
    }
}
Also used : CQLStatement(org.apache.cassandra.cql3.CQLStatement) ProtocolException(org.apache.cassandra.transport.ProtocolException) QueryHandler(org.apache.cassandra.cql3.QueryHandler) Message(org.apache.cassandra.transport.Message) PreparedQueryNotFoundException(org.apache.cassandra.exceptions.PreparedQueryNotFoundException) QueryOptions(org.apache.cassandra.cql3.QueryOptions) PreparedQueryNotFoundException(org.apache.cassandra.exceptions.PreparedQueryNotFoundException) ProtocolException(org.apache.cassandra.transport.ProtocolException) BatchStatement(org.apache.cassandra.cql3.statements.BatchStatement) ResultSet(org.apache.cassandra.cql3.ResultSet)

Example 9 with QueryHandler

use of org.apache.cassandra.cql3.QueryHandler in project cassandra by apache.

the class MessagePayloadTest method testMessagePayloadVersion3.

@Test
public void testMessagePayloadVersion3() throws Throwable {
    QueryHandler queryHandler = (QueryHandler) cqlQueryHandlerField.get(null);
    cqlQueryHandlerField.set(null, new TestQueryHandler());
    try {
        requireNetwork();
        Assert.assertSame(TestQueryHandler.class, ClientState.getCQLQueryHandler().getClass());
        SimpleClient client = new SimpleClient(nativeAddr.getHostAddress(), nativePort, ProtocolVersion.V3);
        try {
            client.connect(false);
            Map<String, ByteBuffer> reqMap;
            QueryMessage queryMessage = new QueryMessage("CREATE TABLE " + KEYSPACE + ".atable (pk int PRIMARY KEY, v text)", QueryOptions.DEFAULT);
            PrepareMessage prepareMessage = new PrepareMessage("SELECT * FROM " + KEYSPACE + ".atable", null);
            reqMap = Collections.singletonMap("foo", bytes(42));
            responsePayload = Collections.singletonMap("bar", bytes(42));
            queryMessage.setCustomPayload(reqMap);
            try {
                client.execute(queryMessage);
                Assert.fail();
            } catch (RuntimeException e) {
                Assert.assertTrue(e.getCause() instanceof ProtocolException);
            }
            // when a protocol exception is thrown by the server the connection is closed, so need to re-connect
            client.close();
            client.connect(false);
            queryMessage.setCustomPayload(null);
            client.execute(queryMessage);
            reqMap = Collections.singletonMap("foo", bytes(43));
            responsePayload = Collections.singletonMap("bar", bytes(43));
            prepareMessage.setCustomPayload(reqMap);
            try {
                client.execute(prepareMessage);
                Assert.fail();
            } catch (RuntimeException e) {
                Assert.assertTrue(e.getCause() instanceof ProtocolException);
            }
            // when a protocol exception is thrown by the server the connection is closed, so need to re-connect
            client.close();
            client.connect(false);
            prepareMessage.setCustomPayload(null);
            ResultMessage.Prepared prepareResponse = (ResultMessage.Prepared) client.execute(prepareMessage);
            ExecuteMessage executeMessage = new ExecuteMessage(prepareResponse.statementId, prepareResponse.resultMetadataId, QueryOptions.DEFAULT);
            reqMap = Collections.singletonMap("foo", bytes(44));
            responsePayload = Collections.singletonMap("bar", bytes(44));
            executeMessage.setCustomPayload(reqMap);
            try {
                client.execute(executeMessage);
                Assert.fail();
            } catch (RuntimeException e) {
                Assert.assertTrue(e.getCause() instanceof ProtocolException);
            }
            // when a protocol exception is thrown by the server the connection is closed, so need to re-connect
            client.close();
            client.connect(false);
            BatchMessage batchMessage = new BatchMessage(BatchStatement.Type.UNLOGGED, Collections.<Object>singletonList("INSERT INTO " + KEYSPACE + ".atable (pk,v) VALUES (1, 'foo')"), Collections.singletonList(Collections.<ByteBuffer>emptyList()), QueryOptions.DEFAULT);
            reqMap = Collections.singletonMap("foo", bytes(45));
            responsePayload = Collections.singletonMap("bar", bytes(45));
            batchMessage.setCustomPayload(reqMap);
            try {
                client.execute(batchMessage);
                Assert.fail();
            } catch (RuntimeException e) {
                Assert.assertTrue(e.getCause() instanceof ProtocolException);
            }
        } finally {
            client.close();
        }
    } finally {
        cqlQueryHandlerField.set(null, queryHandler);
    }
}
Also used : QueryMessage(org.apache.cassandra.transport.messages.QueryMessage) QueryHandler(org.apache.cassandra.cql3.QueryHandler) ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) ByteBuffer(java.nio.ByteBuffer) PrepareMessage(org.apache.cassandra.transport.messages.PrepareMessage) ExecuteMessage(org.apache.cassandra.transport.messages.ExecuteMessage) BatchMessage(org.apache.cassandra.transport.messages.BatchMessage) Test(org.junit.Test)

Aggregations

QueryHandler (org.apache.cassandra.cql3.QueryHandler)8 ByteBuffer (java.nio.ByteBuffer)5 CQLStatement (org.apache.cassandra.cql3.CQLStatement)4 PreparedQueryNotFoundException (org.apache.cassandra.exceptions.PreparedQueryNotFoundException)4 QueryOptions (org.apache.cassandra.cql3.QueryOptions)3 BatchStatement (org.apache.cassandra.cql3.statements.BatchStatement)3 Message (org.apache.cassandra.transport.Message)3 ProtocolException (org.apache.cassandra.transport.ProtocolException)3 BatchMessage (org.apache.cassandra.transport.messages.BatchMessage)3 ExecuteMessage (org.apache.cassandra.transport.messages.ExecuteMessage)3 PrepareMessage (org.apache.cassandra.transport.messages.PrepareMessage)3 QueryMessage (org.apache.cassandra.transport.messages.QueryMessage)3 ResultMessage (org.apache.cassandra.transport.messages.ResultMessage)3 Test (org.junit.Test)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 ArrayList (java.util.ArrayList)2 UUID (java.util.UUID)2 BatchQueryOptions (org.apache.cassandra.cql3.BatchQueryOptions)2 ModificationStatement (org.apache.cassandra.cql3.statements.ModificationStatement)2 ParsedStatement (org.apache.cassandra.cql3.statements.ParsedStatement)2