Search in sources :

Example 1 with BatchStatement

use of org.apache.cassandra.cql3.statements.BatchStatement 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 BatchStatement

use of org.apache.cassandra.cql3.statements.BatchStatement in project cassandra by apache.

the class CustomNowInSecondsTest method testBatchMessage.

@Test
public void testBatchMessage() {
    // test BatchMessage path
    int now = (int) (System.currentTimeMillis() / 1000);
    int day = 86400;
    String ks = createKeyspace("CREATE KEYSPACE %s WITH replication={ 'class' : 'SimpleStrategy', 'replication_factor' : 1 }");
    String tbl = createTable(ks, "CREATE TABLE %s (id int primary key, val int)");
    List<String> queries = ImmutableList.of(format("INSERT INTO %s.%s (id, val) VALUES (0, 0) USING TTL %d;", ks, tbl, 1), format("INSERT INTO %s.%s (id, val) VALUES (1, 1) USING TTL %d;", ks, tbl, 1));
    ClientState cs = ClientState.forInternalCalls();
    QueryState qs = new QueryState(cs);
    List<ModificationStatement> statements = new ArrayList<>(queries.size());
    for (String query : queries) statements.add((ModificationStatement) QueryProcessor.parseStatement(query, cs));
    BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED, VariableSpecifications.empty(), statements, Attributes.none());
    // execute an BATCH message with now set to [now + 1 day], with ttl = 1, making its effective ttl = 1 day + 1.
    QueryProcessor.instance.processBatch(batch, qs, batchQueryOptions(now + day), emptyMap(), nanoTime());
    // verify that despite TTL having passed at now + 1 the rows are still there.
    assertEquals(2, executeSelect(format("SELECT * FROM %s.%s", ks, tbl), now + 1, false).size());
    // jump in time by one day, make sure the row expired.
    assertEquals(0, executeSelect(format("SELECT * FROM %s.%s", ks, tbl), now + day + 1, false).size());
}
Also used : ClientState(org.apache.cassandra.service.ClientState) ModificationStatement(org.apache.cassandra.cql3.statements.ModificationStatement) BatchStatement(org.apache.cassandra.cql3.statements.BatchStatement) ArrayList(java.util.ArrayList) QueryState(org.apache.cassandra.service.QueryState) Test(org.junit.Test)

Example 3 with BatchStatement

use of org.apache.cassandra.cql3.statements.BatchStatement in project cassandra by apache.

the class CassandraAuthorizer method executeLoggedBatch.

private void executeLoggedBatch(List<CQLStatement> statements) throws RequestExecutionException, RequestValidationException {
    BatchStatement batch = new BatchStatement(BatchStatement.Type.LOGGED, VariableSpecifications.empty(), Lists.newArrayList(Iterables.filter(statements, ModificationStatement.class)), Attributes.none());
    processBatch(batch);
}
Also used : BatchStatement(org.apache.cassandra.cql3.statements.BatchStatement)

Example 4 with BatchStatement

use of org.apache.cassandra.cql3.statements.BatchStatement in project cassandra by apache.

the class BatchStatementBench method setup.

@Setup
public void setup() throws Throwable {
    Schema.instance.load(KeyspaceMetadata.create(keyspace, KeyspaceParams.simple(1)));
    KeyspaceMetadata ksm = Schema.instance.getKeyspaceMetadata(keyspace);
    TableMetadata metadata = CreateTableStatement.parse(String.format("CREATE TABLE %s (id int, ck int, v int, primary key (id, ck))", table), keyspace).build();
    Schema.instance.load(ksm.withSwapped(ksm.tables.with(metadata)));
    List<ModificationStatement> modifications = new ArrayList<>(batchSize);
    List<List<ByteBuffer>> parameters = new ArrayList<>(batchSize);
    List<Object> queryOrIdList = new ArrayList<>(batchSize);
    QueryHandler.Prepared prepared = QueryProcessor.prepareInternal(String.format("INSERT INTO %s.%s (id, ck, v) VALUES (?,?,?)", keyspace, table));
    for (int i = 0; i < batchSize; i++) {
        modifications.add((ModificationStatement) prepared.statement);
        parameters.add(Lists.newArrayList(bytes(uniquePartition ? i : 1), bytes(i), bytes(i)));
        queryOrIdList.add(prepared.rawCQLStatement);
    }
    bs = new BatchStatement(BatchStatement.Type.UNLOGGED, VariableSpecifications.empty(), modifications, Attributes.none());
    bqo = BatchQueryOptions.withPerStatementVariables(QueryOptions.DEFAULT, parameters, queryOrIdList);
}
Also used : TableMetadata(org.apache.cassandra.schema.TableMetadata) QueryHandler(org.apache.cassandra.cql3.QueryHandler) ModificationStatement(org.apache.cassandra.cql3.statements.ModificationStatement) ArrayList(java.util.ArrayList) BatchStatement(org.apache.cassandra.cql3.statements.BatchStatement) ArrayList(java.util.ArrayList) List(java.util.List) KeyspaceMetadata(org.apache.cassandra.schema.KeyspaceMetadata) Setup(org.openjdk.jmh.annotations.Setup)

Example 5 with BatchStatement

use of org.apache.cassandra.cql3.statements.BatchStatement in project cassandra by apache.

the class UFIdentificationTest method testBatchStatement.

@Test
public void testBatchStatement() throws Throwable {
    String iFunc2 = createEchoFunction("int");
    List<ModificationStatement> statements = new ArrayList<>();
    statements.add(modificationStatement(cql("INSERT INTO %s (key, i_cc, t_cc) VALUES (%s, 0, 'foo')", functionCall(iFunc, "0"))));
    statements.add(modificationStatement(cql("INSERT INTO %s (key, i_cc, t_cc) VALUES (1, %s, 'foo')", functionCall(iFunc2, "1"))));
    statements.add(modificationStatement(cql("INSERT INTO %s (key, i_cc, t_cc) VALUES (2, 2, %s)", functionCall(tFunc, "'foo'"))));
    BatchStatement batch = new BatchStatement(BatchStatement.Type.LOGGED, VariableSpecifications.empty(), statements, Attributes.none());
    assertFunctions(batch, iFunc, iFunc2, tFunc);
}
Also used : ModificationStatement(org.apache.cassandra.cql3.statements.ModificationStatement) BatchStatement(org.apache.cassandra.cql3.statements.BatchStatement) Test(org.junit.Test)

Aggregations

BatchStatement (org.apache.cassandra.cql3.statements.BatchStatement)9 ModificationStatement (org.apache.cassandra.cql3.statements.ModificationStatement)7 ArrayList (java.util.ArrayList)4 Test (org.junit.Test)4 QueryHandler (org.apache.cassandra.cql3.QueryHandler)3 PreparedQueryNotFoundException (org.apache.cassandra.exceptions.PreparedQueryNotFoundException)3 ByteBuffer (java.nio.ByteBuffer)2 CQLStatement (org.apache.cassandra.cql3.CQLStatement)2 InvalidRequestException (org.apache.cassandra.exceptions.InvalidRequestException)2 Message (org.apache.cassandra.transport.Message)2 ProtocolException (org.apache.cassandra.transport.ProtocolException)2 MD5Digest (org.apache.cassandra.utils.MD5Digest)2 ImmutableMap (com.google.common.collect.ImmutableMap)1 List (java.util.List)1 UUID (java.util.UUID)1 BatchQueryOptions (org.apache.cassandra.cql3.BatchQueryOptions)1 QueryOptions (org.apache.cassandra.cql3.QueryOptions)1 ResultSet (org.apache.cassandra.cql3.ResultSet)1 ParsedStatement (org.apache.cassandra.cql3.statements.ParsedStatement)1 KeyspaceMetadata (org.apache.cassandra.schema.KeyspaceMetadata)1