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