Search in sources :

Example 1 with QueryHandler

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

the class BatchMessage method execute.

public Message.Response execute(QueryState state, long queryStartNanoTime) {
    try {
        UUID tracingId = null;
        if (isTracingRequested()) {
            tracingId = UUIDGen.getTimeUUID();
            state.prepareTracingSession(tracingId);
        }
        if (state.traceNextQuery()) {
            state.createTracingSession();
            ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
            if (options.getConsistency() != null)
                builder.put("consistency_level", options.getConsistency().name());
            if (options.getSerialConsistency() != null)
                builder.put("serial_consistency_level", options.getSerialConsistency().name());
            // TODO we don't have [typed] access to CQL bind variables here.  CASSANDRA-4560 is open to add support.
            Tracing.instance.begin("Execute batch of CQL3 queries", state.getClientAddress(), builder.build());
        }
        QueryHandler handler = ClientState.getCQLQueryHandler();
        List<ParsedStatement.Prepared> prepared = new ArrayList<>(queryOrIdList.size());
        for (int i = 0; i < queryOrIdList.size(); i++) {
            Object query = queryOrIdList.get(i);
            ParsedStatement.Prepared p;
            if (query instanceof String) {
                p = QueryProcessor.parseStatement((String) query, state);
            } else {
                p = handler.getPrepared((MD5Digest) query);
                if (p == null)
                    throw new PreparedQueryNotFoundException((MD5Digest) query);
            }
            List<ByteBuffer> queryValues = values.get(i);
            if (queryValues.size() != p.statement.getBoundTerms())
                throw new InvalidRequestException(String.format("There were %d markers(?) in CQL but %d bound variables", p.statement.getBoundTerms(), queryValues.size()));
            prepared.add(p);
        }
        BatchQueryOptions batchOptions = BatchQueryOptions.withPerStatementVariables(options, values, queryOrIdList);
        List<ModificationStatement> statements = new ArrayList<>(prepared.size());
        for (int i = 0; i < prepared.size(); i++) {
            ParsedStatement.Prepared p = prepared.get(i);
            batchOptions.prepareStatement(i, p.boundNames);
            if (!(p.statement instanceof ModificationStatement))
                throw new InvalidRequestException("Invalid statement in batch: only UPDATE, INSERT and DELETE statements are allowed.");
            statements.add((ModificationStatement) p.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(-1, batchType, statements, Attributes.none());
        Message.Response response = handler.processBatch(batch, state, batchOptions, getCustomPayload(), queryStartNanoTime);
        if (tracingId != null)
            response.setTracingId(tracingId);
        return response;
    } catch (Exception e) {
        JVMStabilityInspector.inspectThrowable(e);
        return ErrorMessage.fromException(e);
    } finally {
        Tracing.instance.stopSession();
    }
}
Also used : ModificationStatement(org.apache.cassandra.cql3.statements.ModificationStatement) ArrayList(java.util.ArrayList) ParsedStatement(org.apache.cassandra.cql3.statements.ParsedStatement) PreparedQueryNotFoundException(org.apache.cassandra.exceptions.PreparedQueryNotFoundException) ByteBuffer(java.nio.ByteBuffer) ImmutableMap(com.google.common.collect.ImmutableMap) PreparedQueryNotFoundException(org.apache.cassandra.exceptions.PreparedQueryNotFoundException) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException) MD5Digest(org.apache.cassandra.utils.MD5Digest) BatchStatement(org.apache.cassandra.cql3.statements.BatchStatement) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException) UUID(java.util.UUID)

Example 2 with QueryHandler

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

the class ExecuteMessage method execute.

public Message.Response execute(QueryState state, long queryStartNanoTime) {
    try {
        QueryHandler handler = ClientState.getCQLQueryHandler();
        ParsedStatement.Prepared prepared = handler.getPrepared(statementId);
        if (prepared == null)
            throw new PreparedQueryNotFoundException(statementId);
        options.prepare(prepared.boundNames);
        CQLStatement statement = prepared.statement;
        if (options.getPageSize() == 0)
            throw new ProtocolException("The page size cannot be 0");
        UUID tracingId = null;
        if (isTracingRequested()) {
            tracingId = UUIDGen.getTimeUUID();
            state.prepareTracingSession(tracingId);
        }
        if (state.traceNextQuery()) {
            state.createTracingSession(getCustomPayload());
            ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
            if (options.getPageSize() > 0)
                builder.put("page_size", Integer.toString(options.getPageSize()));
            if (options.getConsistency() != null)
                builder.put("consistency_level", options.getConsistency().name());
            if (options.getSerialConsistency() != null)
                builder.put("serial_consistency_level", options.getSerialConsistency().name());
            builder.put("query", prepared.rawCQLStatement);
            for (int i = 0; i < prepared.boundNames.size(); i++) {
                ColumnSpecification cs = prepared.boundNames.get(i);
                String boundName = cs.name.toString();
                String boundValue = cs.type.asCQL3Type().toCQLLiteral(options.getValues().get(i), options.getProtocolVersion());
                if (boundValue.length() > 1000) {
                    boundValue = boundValue.substring(0, 1000) + "...'";
                }
                //Here we prefix boundName with the index to avoid possible collission in builder keys due to
                //having multiple boundValues for the same variable
                builder.put("bound_var_" + Integer.toString(i) + "_" + boundName, boundValue);
            }
            Tracing.instance.begin("Execute CQL3 prepared query", state.getClientAddress(), builder.build());
        }
        // Some custom QueryHandlers are interested by the bound names. We provide them this information
        // by wrapping the QueryOptions.
        QueryOptions queryOptions = QueryOptions.addColumnSpecifications(options, prepared.boundNames);
        Message.Response response = handler.processPrepared(statement, state, queryOptions, getCustomPayload(), queryStartNanoTime);
        if (options.skipMetadata() && response instanceof ResultMessage.Rows)
            ((ResultMessage.Rows) response).result.metadata.setSkipMetadata();
        if (tracingId != null)
            response.setTracingId(tracingId);
        return response;
    } catch (Exception e) {
        JVMStabilityInspector.inspectThrowable(e);
        return ErrorMessage.fromException(e);
    } finally {
        Tracing.instance.stopSession();
    }
}
Also used : CQLStatement(org.apache.cassandra.cql3.CQLStatement) QueryHandler(org.apache.cassandra.cql3.QueryHandler) ColumnSpecification(org.apache.cassandra.cql3.ColumnSpecification) ParsedStatement(org.apache.cassandra.cql3.statements.ParsedStatement) PreparedQueryNotFoundException(org.apache.cassandra.exceptions.PreparedQueryNotFoundException) QueryOptions(org.apache.cassandra.cql3.QueryOptions) ImmutableMap(com.google.common.collect.ImmutableMap) PreparedQueryNotFoundException(org.apache.cassandra.exceptions.PreparedQueryNotFoundException) UUID(java.util.UUID)

Example 3 with QueryHandler

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

the class QueryMessage method execute.

@Override
protected Message.Response execute(QueryState state, long queryStartNanoTime, boolean traceRequest) {
    CQLStatement statement = null;
    try {
        if (options.getPageSize() == 0)
            throw new ProtocolException("The page size cannot be 0");
        if (traceRequest)
            traceQuery(state);
        long queryStartTime = currentTimeMillis();
        QueryHandler queryHandler = ClientState.getCQLQueryHandler();
        statement = queryHandler.parse(query, state, options);
        Message.Response response = queryHandler.process(statement, state, options, getCustomPayload(), queryStartNanoTime);
        QueryEvents.instance.notifyQuerySuccess(statement, query, options, state, queryStartTime, response);
        if (options.skipMetadata() && response instanceof ResultMessage.Rows)
            ((ResultMessage.Rows) response).result.metadata.setSkipMetadata();
        return response;
    } catch (Exception e) {
        QueryEvents.instance.notifyQueryFailure(statement, query, options, state, e);
        JVMStabilityInspector.inspectThrowable(e);
        if (!((e instanceof RequestValidationException) || (e instanceof RequestExecutionException)))
            logger.error("Unexpected error during query", 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) RequestExecutionException(org.apache.cassandra.exceptions.RequestExecutionException) Message(org.apache.cassandra.transport.Message) RequestValidationException(org.apache.cassandra.exceptions.RequestValidationException) RequestExecutionException(org.apache.cassandra.exceptions.RequestExecutionException) RequestValidationException(org.apache.cassandra.exceptions.RequestValidationException) ProtocolException(org.apache.cassandra.transport.ProtocolException)

Example 4 with QueryHandler

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

the class MessagePayloadTest method testMessagePayloadBeta.

@Test
public void testMessagePayloadBeta() 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.V5, true, new EncryptionOptions());
        try {
            client.connect(false);
            Map<String, ByteBuffer> reqMap;
            Map<String, ByteBuffer> respMap;
            QueryOptions queryOptions = QueryOptions.create(QueryOptions.DEFAULT.getConsistency(), QueryOptions.DEFAULT.getValues(), QueryOptions.DEFAULT.skipMetadata(), QueryOptions.DEFAULT.getPageSize(), QueryOptions.DEFAULT.getPagingState(), QueryOptions.DEFAULT.getSerialConsistency(), ProtocolVersion.V5, KEYSPACE);
            QueryMessage queryMessage = new QueryMessage("CREATE TABLE atable (pk int PRIMARY KEY, v text)", queryOptions);
            PrepareMessage prepareMessage = new PrepareMessage("SELECT * FROM atable", KEYSPACE);
            reqMap = Collections.singletonMap("foo", bytes(42));
            responsePayload = respMap = Collections.singletonMap("bar", bytes(42));
            queryMessage.setCustomPayload(reqMap);
            Message.Response queryResponse = client.execute(queryMessage);
            payloadEquals(reqMap, requestPayload);
            payloadEquals(respMap, queryResponse.getCustomPayload());
            reqMap = Collections.singletonMap("foo", bytes(43));
            responsePayload = respMap = Collections.singletonMap("bar", bytes(43));
            prepareMessage.setCustomPayload(reqMap);
            ResultMessage.Prepared prepareResponse = (ResultMessage.Prepared) client.execute(prepareMessage);
            payloadEquals(reqMap, requestPayload);
            payloadEquals(respMap, prepareResponse.getCustomPayload());
            ExecuteMessage executeMessage = new ExecuteMessage(prepareResponse.statementId, prepareResponse.resultMetadataId, QueryOptions.DEFAULT);
            reqMap = Collections.singletonMap("foo", bytes(44));
            responsePayload = respMap = Collections.singletonMap("bar", bytes(44));
            executeMessage.setCustomPayload(reqMap);
            Message.Response executeResponse = client.execute(executeMessage);
            payloadEquals(reqMap, requestPayload);
            payloadEquals(respMap, executeResponse.getCustomPayload());
            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);
            reqMap = Collections.singletonMap("foo", bytes(45));
            responsePayload = respMap = Collections.singletonMap("bar", bytes(45));
            batchMessage.setCustomPayload(reqMap);
            Message.Response batchResponse = client.execute(batchMessage);
            payloadEquals(reqMap, requestPayload);
            payloadEquals(respMap, batchResponse.getCustomPayload());
        } finally {
            client.close();
        }
    } finally {
        cqlQueryHandlerField.set(null, queryHandler);
    }
}
Also used : QueryMessage(org.apache.cassandra.transport.messages.QueryMessage) QueryHandler(org.apache.cassandra.cql3.QueryHandler) BatchMessage(org.apache.cassandra.transport.messages.BatchMessage) PrepareMessage(org.apache.cassandra.transport.messages.PrepareMessage) ExecuteMessage(org.apache.cassandra.transport.messages.ExecuteMessage) ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) QueryMessage(org.apache.cassandra.transport.messages.QueryMessage) ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) ByteBuffer(java.nio.ByteBuffer) BatchQueryOptions(org.apache.cassandra.cql3.BatchQueryOptions) QueryOptions(org.apache.cassandra.cql3.QueryOptions) PrepareMessage(org.apache.cassandra.transport.messages.PrepareMessage) ExecuteMessage(org.apache.cassandra.transport.messages.ExecuteMessage) EncryptionOptions(org.apache.cassandra.config.EncryptionOptions) BatchMessage(org.apache.cassandra.transport.messages.BatchMessage) Test(org.junit.Test)

Example 5 with QueryHandler

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

the class MessagePayloadTest method testMessagePayload.

@Test
public void testMessagePayload() 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);
        try {
            client.connect(false);
            Map<String, ByteBuffer> reqMap;
            Map<String, ByteBuffer> respMap;
            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 = respMap = Collections.singletonMap("bar", bytes(42));
            queryMessage.setCustomPayload(reqMap);
            Message.Response queryResponse = client.execute(queryMessage);
            payloadEquals(reqMap, requestPayload);
            payloadEquals(respMap, queryResponse.getCustomPayload());
            reqMap = Collections.singletonMap("foo", bytes(43));
            responsePayload = respMap = Collections.singletonMap("bar", bytes(43));
            prepareMessage.setCustomPayload(reqMap);
            ResultMessage.Prepared prepareResponse = (ResultMessage.Prepared) client.execute(prepareMessage);
            payloadEquals(reqMap, requestPayload);
            payloadEquals(respMap, prepareResponse.getCustomPayload());
            ExecuteMessage executeMessage = new ExecuteMessage(prepareResponse.statementId, prepareResponse.resultMetadataId, QueryOptions.DEFAULT);
            reqMap = Collections.singletonMap("foo", bytes(44));
            responsePayload = respMap = Collections.singletonMap("bar", bytes(44));
            executeMessage.setCustomPayload(reqMap);
            Message.Response executeResponse = client.execute(executeMessage);
            payloadEquals(reqMap, requestPayload);
            payloadEquals(respMap, executeResponse.getCustomPayload());
            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 = respMap = Collections.singletonMap("bar", bytes(45));
            batchMessage.setCustomPayload(reqMap);
            Message.Response batchResponse = client.execute(batchMessage);
            payloadEquals(reqMap, requestPayload);
            payloadEquals(respMap, batchResponse.getCustomPayload());
        } finally {
            client.close();
        }
    } finally {
        cqlQueryHandlerField.set(null, queryHandler);
    }
}
Also used : QueryMessage(org.apache.cassandra.transport.messages.QueryMessage) QueryHandler(org.apache.cassandra.cql3.QueryHandler) BatchMessage(org.apache.cassandra.transport.messages.BatchMessage) PrepareMessage(org.apache.cassandra.transport.messages.PrepareMessage) ExecuteMessage(org.apache.cassandra.transport.messages.ExecuteMessage) ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) QueryMessage(org.apache.cassandra.transport.messages.QueryMessage) 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