Search in sources :

Example 26 with SimpleStatement

use of com.datastax.driver.core.SimpleStatement in project java-driver by datastax.

the class MapperAsyncResultTest method should_iterate_result_set_asynchronously.

private void should_iterate_result_set_asynchronously(int totalCount, int fetchSize) {
    for (int i = 0; i < totalCount; i++) session().execute(String.format("INSERT INTO users (id, name) values (%d, '%s')", i, "user" + i));
    Statement statement = new SimpleStatement("SELECT * FROM users").setFetchSize(fetchSize);
    Mapper<User> mapper = new MappingManager(session()).mapper(User.class);
    ResultsAccumulator accumulator = new ResultsAccumulator();
    ListenableFuture<Result<User>> results = mapper.mapAsync(session().executeAsync(statement));
    ListenableFuture<Result<User>> future = GuavaCompatibility.INSTANCE.transformAsync(results, accumulator);
    Futures.getUnchecked(future);
    assertThat(accumulator.all.size()).isEqualTo(totalCount);
}
Also used : SimpleStatement(com.datastax.driver.core.SimpleStatement) Statement(com.datastax.driver.core.Statement) SimpleStatement(com.datastax.driver.core.SimpleStatement)

Example 27 with SimpleStatement

use of com.datastax.driver.core.SimpleStatement in project java-driver by datastax.

the class DowngradingRetry method write.

/**
 * Inserts data, retrying if necessary with a downgraded CL.
 *
 * @param cl         the consistency level to apply.
 * @param retryCount the current retry count.
 * @throws DriverException if the current consistency level cannot be downgraded.
 */
private void write(ConsistencyLevel cl, int retryCount) {
    System.out.printf("Writing at %s (retry count: %d)%n", cl, retryCount);
    BatchStatement batch = new BatchStatement(UNLOGGED);
    batch.add(new SimpleStatement("INSERT INTO downgrading.sensor_data " + "(sensor_id, date, timestamp, value) " + "VALUES (" + "756716f7-2e54-4715-9f00-91dcbea6cf50," + "'2018-02-26'," + "'2018-02-26T13:53:46.345+01:00'," + "2.34)"));
    batch.add(new SimpleStatement("INSERT INTO downgrading.sensor_data " + "(sensor_id, date, timestamp, value) " + "VALUES (" + "756716f7-2e54-4715-9f00-91dcbea6cf50," + "'2018-02-26'," + "'2018-02-26T13:54:27.488+01:00'," + "2.47)"));
    batch.add(new SimpleStatement("INSERT INTO downgrading.sensor_data " + "(sensor_id, date, timestamp, value) " + "VALUES (" + "756716f7-2e54-4715-9f00-91dcbea6cf50," + "'2018-02-26'," + "'2018-02-26T13:56:33.739+01:00'," + "2.52)"));
    batch.setConsistencyLevel(cl);
    try {
        session.execute(batch);
        System.out.println("Write succeeded at " + cl);
    } catch (DriverException e) {
        if (retryCount == maxRetries) {
            throw e;
        }
        e = unwrapNoHostAvailableException(e);
        System.out.println("Write failed: " + e);
        if (e instanceof UnavailableException) {
            // With an UnavailableException, we know that the write wasn't even attempted.
            // Downgrade to the number of replicas reported alive and retry.
            int aliveReplicas = ((UnavailableException) e).getAliveReplicas();
            ConsistencyLevel downgraded = downgrade(cl, aliveReplicas, e);
            write(downgraded, retryCount + 1);
        } else if (e instanceof WriteTimeoutException) {
            WriteType writeType = ((WriteTimeoutException) e).getWriteType();
            int acknowledgements = ((WriteTimeoutException) e).getReceivedAcknowledgements();
            switch(writeType) {
                case SIMPLE:
                case BATCH:
                    // a retry would ever succeed.
                    if (acknowledgements == 0) {
                        throw e;
                    }
                    break;
                case UNLOGGED_BATCH:
                    // For unlogged batches, the write might have been persisted only partially,
                    // so we can't simply ignore the exception: instead, we need to retry with
                    // consistency level equal to the number of acknowledged writes.
                    ConsistencyLevel downgraded = downgrade(cl, acknowledgements, e);
                    write(downgraded, retryCount + 1);
                    break;
                case BATCH_LOG:
                    // Rare edge case: the peers that were chosen by the coordinator
                    // to receive the distributed batch log failed to respond.
                    // Simply retry with same consistency level.
                    write(cl, retryCount + 1);
                    break;
                default:
                    // Other write types are uncommon and should not be retried.
                    throw e;
            }
        } else {
            // Unexpected error: just retry with same consistency level
            // and hope to talk to a healthier coordinator.
            write(cl, retryCount + 1);
        }
    }
}
Also used : ConsistencyLevel(com.datastax.driver.core.ConsistencyLevel) WriteTimeoutException(com.datastax.driver.core.exceptions.WriteTimeoutException) SimpleStatement(com.datastax.driver.core.SimpleStatement) WriteType(com.datastax.driver.core.WriteType) BatchStatement(com.datastax.driver.core.BatchStatement) UnavailableException(com.datastax.driver.core.exceptions.UnavailableException) DriverException(com.datastax.driver.core.exceptions.DriverException)

Example 28 with SimpleStatement

use of com.datastax.driver.core.SimpleStatement in project cassandra by apache.

the class PagingTest method checkDuplicates.

private void checkDuplicates(String message) throws InterruptedException {
    // sometimes one node doesn't have time come up properly?
    Thread.sleep(5000);
    try (com.datastax.driver.core.Cluster c = com.datastax.driver.core.Cluster.builder().addContactPoint("127.0.0.1").withProtocolVersion(ProtocolVersion.V3).withQueryOptions(new QueryOptions().setFetchSize(101)).build();
        Session s = c.connect()) {
        Statement stmt = new SimpleStatement("select distinct token(pk) from " + DistributedTestBase.KEYSPACE + ".tbl WHERE token(pk) > " + Long.MIN_VALUE + " AND token(pk) < " + Long.MAX_VALUE);
        stmt.setConsistencyLevel(com.datastax.driver.core.ConsistencyLevel.ALL);
        ResultSet res = s.execute(stmt);
        Set<Object> seenTokens = new HashSet<>();
        Iterator<Row> rows = res.iterator();
        Set<Object> dupes = new HashSet<>();
        while (rows.hasNext()) {
            Object token = rows.next().getObject(0);
            if (seenTokens.contains(token))
                dupes.add(token);
            seenTokens.add(token);
        }
        assertEquals(message + ": too few rows", 5000, seenTokens.size());
        assertTrue(message + ": dupes is not empty", dupes.isEmpty());
    }
}
Also used : SimpleStatement(com.datastax.driver.core.SimpleStatement) Statement(com.datastax.driver.core.Statement) SimpleStatement(com.datastax.driver.core.SimpleStatement) QueryOptions(com.datastax.driver.core.QueryOptions) ResultSet(com.datastax.driver.core.ResultSet) Row(com.datastax.driver.core.Row) Session(com.datastax.driver.core.Session) HashSet(java.util.HashSet)

Example 29 with SimpleStatement

use of com.datastax.driver.core.SimpleStatement in project cassandra by apache.

the class NativeProtocolTest method withClientRequests.

@Test
public void withClientRequests() throws Throwable {
    try (ICluster ignored = init(builder().withNodes(3).withConfig(config -> config.with(GOSSIP, NETWORK, NATIVE_PROTOCOL)).start())) {
        try (com.datastax.driver.core.Cluster cluster = com.datastax.driver.core.Cluster.builder().addContactPoint("127.0.0.1").build();
            Session session = cluster.connect()) {
            session.execute("CREATE TABLE " + KEYSPACE + ".tbl (pk int, ck int, v int, PRIMARY KEY (pk, ck));");
            session.execute("INSERT INTO " + KEYSPACE + ".tbl (pk, ck, v) values (1,1,1);");
            Statement select = new SimpleStatement("select * from " + KEYSPACE + ".tbl;").setConsistencyLevel(ConsistencyLevel.ALL);
            final ResultSet resultSet = session.execute(select);
            assertRows(RowUtil.toObjects(resultSet), row(1, 1, 1));
            Assert.assertEquals(3, cluster.getMetadata().getAllHosts().size());
        }
    }
}
Also used : SimpleStatement(com.datastax.driver.core.SimpleStatement) CQLStatement(org.apache.cassandra.cql3.CQLStatement) Statement(com.datastax.driver.core.Statement) SimpleStatement(com.datastax.driver.core.SimpleStatement) ICluster(org.apache.cassandra.distributed.api.ICluster) ResultSet(com.datastax.driver.core.ResultSet) Session(com.datastax.driver.core.Session) Test(org.junit.Test)

Example 30 with SimpleStatement

use of com.datastax.driver.core.SimpleStatement in project cassandra by apache.

the class BurnTestUtil method generateQueryStatement.

public static SimpleStatement generateQueryStatement(int idx, SizeCaps sizeCaps) {
    Random rnd = new Random(idx);
    ByteBuffer[] values = new ByteBuffer[sizeCaps.columnCountCap];
    for (int i = 0; i < sizeCaps.columnCountCap; i++) values[i] = bytes(rnd, sizeCaps.valueMinSize, sizeCaps.valueMaxSize);
    return new SimpleStatement(Integer.toString(idx), (Object[]) values);
}
Also used : Random(java.util.Random) SimpleStatement(com.datastax.driver.core.SimpleStatement) ByteBuffer(java.nio.ByteBuffer)

Aggregations

SimpleStatement (com.datastax.driver.core.SimpleStatement)38 ResultSet (com.datastax.driver.core.ResultSet)17 Row (com.datastax.driver.core.Row)17 Test (org.junit.Test)15 Session (com.datastax.driver.core.Session)13 Statement (com.datastax.driver.core.Statement)10 ArrayList (java.util.ArrayList)10 CassandraResultSet (org.apache.gora.cassandra.query.CassandraResultSet)7 GoraException (org.apache.gora.util.GoraException)7 InvalidQueryException (com.datastax.driver.core.exceptions.InvalidQueryException)6 ByteBuffer (java.nio.ByteBuffer)5 ColumnDefinitions (com.datastax.driver.core.ColumnDefinitions)4 AbstractGettableData (com.datastax.driver.core.AbstractGettableData)3 BatchStatement (com.datastax.driver.core.BatchStatement)2 ConsistencyLevel (com.datastax.driver.core.ConsistencyLevel)2 DriverException (com.datastax.driver.core.exceptions.DriverException)2 UnavailableException (com.datastax.driver.core.exceptions.UnavailableException)2 CQLStatement (org.apache.cassandra.cql3.CQLStatement)2 BatchStatement (org.apache.cassandra.cql3.statements.BatchStatement)2 ICluster (org.apache.cassandra.distributed.api.ICluster)2