Search in sources :

Example 31 with SimpleStatement

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

the class QueryEventsTest method batchTest.

@Test
public void batchTest() {
    createTable("create table %s (id int primary key, v int)");
    BatchMockListener listener = new BatchMockListener(getCurrentColumnFamilyStore());
    QueryEvents.instance.registerListener(listener);
    Session session = sessionNet();
    com.datastax.driver.core.BatchStatement batch = new com.datastax.driver.core.BatchStatement(com.datastax.driver.core.BatchStatement.Type.UNLOGGED);
    String q1 = formatQuery("insert into %s (id, v) values (?, ?)");
    PreparedStatement ps = session.prepare(q1);
    batch.add(ps.bind(1, 1));
    batch.add(ps.bind(2, 2));
    String q2 = formatQuery("insert into %s (id, v) values (1,1)");
    batch.add(new SimpleStatement(formatQuery("insert into %s (id, v) values (1,1)")));
    session.execute(batch);
    listener.verify(newArrayList("prepareSuccess", "batchSuccess"), newArrayList(1, 1));
    assertEquals(3, listener.queries.size());
    assertEquals(BatchStatement.Type.UNLOGGED, listener.batchType);
    assertEquals(newArrayList(q1, q1, q2), listener.queries);
    assertEquals(newArrayList(newArrayList(ByteBufferUtil.bytes(1), ByteBufferUtil.bytes(1)), newArrayList(ByteBufferUtil.bytes(2), ByteBufferUtil.bytes(2)), newArrayList(newArrayList())), listener.values);
    batch.add(new SimpleStatement("insert into abc.def (id, v) values (1,1)"));
    try {
        session.execute(batch);
        fail("Batch should fail");
    } catch (Exception e) {
    // ok
    }
    listener.verify(newArrayList("prepareSuccess", "batchSuccess", "batchFailure"), newArrayList(1, 1, 1));
    assertEquals(3, listener.queries.size());
    assertEquals(BatchStatement.Type.UNLOGGED, listener.batchType);
    assertEquals(newArrayList(q1, q1, q2), listener.queries);
    assertEquals(newArrayList(newArrayList(ByteBufferUtil.bytes(1), ByteBufferUtil.bytes(1)), newArrayList(ByteBufferUtil.bytes(2), ByteBufferUtil.bytes(2)), newArrayList(newArrayList()), newArrayList(newArrayList())), listener.values);
}
Also used : SimpleStatement(com.datastax.driver.core.SimpleStatement) BatchStatement(org.apache.cassandra.cql3.statements.BatchStatement) PreparedStatement(com.datastax.driver.core.PreparedStatement) Session(com.datastax.driver.core.Session) Test(org.junit.Test)

Example 32 with SimpleStatement

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

the class PagingTest method testPaging.

/**
 * Makes sure that we don't drop any live rows when paging with DISTINCT queries
 *
 * * We need to have more rows than fetch_size
 * * The node must have a token within the first page (so that the range gets split up in StorageProxy#getRestrictedRanges)
 *   - This means that the second read in the second range will read back too many rows
 * * The extra rows are dropped (so that we only return fetch_size rows to client)
 * * This means that the last row recorded in AbstractQueryPager#recordLast is a non-live one
 * * For the next page, the first row returned will be the same non-live row as above
 * * The bug in CASSANDRA-14956 caused us to drop that non-live row + the first live row in the next page
 */
@Test
public void testPaging() throws InterruptedException {
    String table = KEYSPACE + ".paging";
    String createTableStatement = "CREATE TABLE IF NOT EXISTS " + table + " (id int, id2 int, id3 int, val text, PRIMARY KEY ((id, id2), id3));";
    String dropTableStatement = "DROP TABLE IF EXISTS " + table + ';';
    // custom snitch to avoid merging ranges back together after StorageProxy#getRestrictedRanges splits them up
    IEndpointSnitch snitch = new AbstractEndpointSnitch() {

        private IEndpointSnitch oldSnitch = DatabaseDescriptor.getEndpointSnitch();

        public int compareEndpoints(InetAddressAndPort target, Replica a1, Replica a2) {
            return oldSnitch.compareEndpoints(target, a1, a2);
        }

        public String getRack(InetAddressAndPort endpoint) {
            return oldSnitch.getRack(endpoint);
        }

        public String getDatacenter(InetAddressAndPort endpoint) {
            return oldSnitch.getDatacenter(endpoint);
        }

        @Override
        public boolean isWorthMergingForRangeQuery(ReplicaCollection merged, ReplicaCollection l1, ReplicaCollection l2) {
            return false;
        }
    };
    DatabaseDescriptor.setEndpointSnitch(snitch);
    StorageService.instance.getTokenMetadata().clearUnsafe();
    StorageService.instance.getTokenMetadata().updateNormalToken(new LongToken(5097162189738624638L), FBUtilities.getBroadcastAddressAndPort());
    session.execute(createTableStatement);
    for (int i = 0; i < 110; i++) {
        // removing row with idx 10 causes the last row in the first page read to be empty
        String ttlClause = i == 10 ? "USING TTL 1" : "";
        session.execute(String.format("INSERT INTO %s (id, id2, id3, val) VALUES (%d, %d, %d, '%d') %s", table, i, i, i, i, ttlClause));
    }
    Thread.sleep(1500);
    Statement stmt = new SimpleStatement(String.format("SELECT DISTINCT token(id, id2), id, id2 FROM %s", table));
    stmt.setFetchSize(100);
    ResultSet res = session.execute(stmt);
    stmt.setFetchSize(200);
    ResultSet res2 = session.execute(stmt);
    Iterator<Row> iter1 = res.iterator();
    Iterator<Row> iter2 = res2.iterator();
    while (iter1.hasNext() && iter2.hasNext()) {
        Row row1 = iter1.next();
        Row row2 = iter2.next();
        assertEquals(row1.getInt("id"), row2.getInt("id"));
    }
    assertFalse(iter1.hasNext());
    assertFalse(iter2.hasNext());
    session.execute(dropTableStatement);
}
Also used : SimpleStatement(com.datastax.driver.core.SimpleStatement) Statement(com.datastax.driver.core.Statement) SimpleStatement(com.datastax.driver.core.SimpleStatement) LongToken(org.apache.cassandra.dht.Murmur3Partitioner.LongToken) ResultSet(com.datastax.driver.core.ResultSet) Row(com.datastax.driver.core.Row) Test(org.junit.Test)

Example 33 with SimpleStatement

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

the class CqlInputFormat method queryTableEstimates.

private static ResultSet queryTableEstimates(Session session, Host host, String keyspace, String table, TokenRange tokenRange) {
    try {
        String query = String.format("SELECT mean_partition_size, partitions_count " + "FROM %s.%s " + "WHERE keyspace_name = ? AND table_name = ? AND range_type = '%s' AND range_start = ? AND range_end = ?", SchemaConstants.SYSTEM_KEYSPACE_NAME, SystemKeyspace.TABLE_ESTIMATES, SystemKeyspace.TABLE_ESTIMATES_TYPE_LOCAL_PRIMARY);
        Statement stmt = new SimpleStatement(query, keyspace, table, tokenRange.getStart().toString(), tokenRange.getEnd().toString()).setHost(host);
        return session.execute(stmt);
    } catch (InvalidQueryException e) {
        // if the table doesn't exist, fall back to old table.  This is likely to return no records in a multi
        // DC setup, but should work fine in a single DC setup.
        String query = String.format("SELECT mean_partition_size, partitions_count " + "FROM %s.%s " + "WHERE keyspace_name = ? AND table_name = ? AND range_start = ? AND range_end = ?", SchemaConstants.SYSTEM_KEYSPACE_NAME, SystemKeyspace.LEGACY_SIZE_ESTIMATES);
        Statement stmt = new SimpleStatement(query, keyspace, table, tokenRange.getStart().toString(), tokenRange.getEnd().toString()).setHost(host);
        return session.execute(stmt);
    }
}
Also used : SimpleStatement(com.datastax.driver.core.SimpleStatement) Statement(com.datastax.driver.core.Statement) SimpleStatement(com.datastax.driver.core.SimpleStatement) InvalidQueryException(com.datastax.driver.core.exceptions.InvalidQueryException)

Example 34 with SimpleStatement

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

the class FQLReplayTest method testFQLQuerySingleToStatement.

@Test
public void testFQLQuerySingleToStatement() {
    List<ByteBuffer> values = new ArrayList<>();
    for (int i = 0; i < 10; i++) values.add(ByteBufferUtil.bytes(i));
    FQLQuery.Single single = new FQLQuery.Single("xyz", QueryOptions.DEFAULT.getProtocolVersion().asInt(), QueryOptions.forInternalCalls(values), 1234, 12345, 54321, "select * from aaa", values);
    Statement stmt = single.toStatement();
    assertEquals(stmt.getDefaultTimestamp(), 12345);
    assertTrue(stmt instanceof SimpleStatement);
    SimpleStatement simpleStmt = (SimpleStatement) stmt;
    assertEquals("select * from aaa", simpleStmt.getQueryString(CodecRegistry.DEFAULT_INSTANCE));
    assertArrayEquals(values.toArray(), simpleStmt.getValues(com.datastax.driver.core.ProtocolVersion.fromInt(QueryOptions.DEFAULT.getProtocolVersion().asInt()), CodecRegistry.DEFAULT_INSTANCE));
}
Also used : SimpleStatement(com.datastax.driver.core.SimpleStatement) BatchStatement(org.apache.cassandra.cql3.statements.BatchStatement) Statement(com.datastax.driver.core.Statement) SimpleStatement(com.datastax.driver.core.SimpleStatement) ArrayList(java.util.ArrayList) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 35 with SimpleStatement

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

the class SASICQLTest method testStringLikePrefix.

/**
 * Tests query condition like_prefix on string columns.
 */
@Test
public void testStringLikePrefix() throws Throwable {
    for (String mode : new String[] { "PREFIX", "CONTAINS" }) {
        for (boolean forceFlush : new boolean[] { false, true }) {
            try {
                createTable("CREATE TABLE %s (pk int primary key, v text);");
                createIndex(String.format("CREATE CUSTOM INDEX ON %%s (v) USING 'org.apache.cassandra.index.sasi.SASIIndex' WITH OPTIONS = {'mode': '%s'};", mode));
                execute("INSERT INTO %s (pk, v) VALUES (?, ?);", 0, "a");
                execute("INSERT INTO %s (pk, v) VALUES (?, ?);", 1, "abc");
                execute("INSERT INTO %s (pk, v) VALUES (?, ?);", 2, "ac");
                flush(forceFlush);
                Session session = sessionNet();
                SimpleStatement stmt = new SimpleStatement("SELECT * FROM " + KEYSPACE + '.' + currentTable() + " WHERE v LIKE 'ab%'");
                stmt.setFetchSize(5);
                List<Row> rs = session.execute(stmt).all();
                Assert.assertEquals(1, rs.size());
                Assert.assertEquals(1, rs.get(0).getInt("pk"));
            } catch (Throwable th) {
                throw new AssertionError(String.format("Failure with mode:%s and flush:%s ", mode, forceFlush), th);
            }
        }
    }
}
Also used : SimpleStatement(com.datastax.driver.core.SimpleStatement) Row(com.datastax.driver.core.Row) Session(com.datastax.driver.core.Session) Test(org.junit.Test)

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