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();
}
}
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();
}
}
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);
}
}
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);
}
}
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);
}
}
Aggregations