Search in sources :

Example 71 with UntypedResultSet

use of org.apache.cassandra.cql3.UntypedResultSet in project cassandra by apache.

the class TimeSortTest method validateTimeSort.

private void validateTimeSort() throws Throwable {
    for (int i = 900; i < 1000; ++i) {
        for (int j = 0; j < 8; j += 3) {
            UntypedResultSet results = execute("SELECT writetime(c) AS wt FROM %s WHERE a = ? AND b >= ? LIMIT 1000", i, j * 2);
            assertEquals(8 - j, results.size());
            int k = j;
            for (UntypedResultSet.Row row : results) assertEquals((k++) * 2, row.getLong("wt"));
        }
    }
}
Also used : UntypedResultSet(org.apache.cassandra.cql3.UntypedResultSet)

Example 72 with UntypedResultSet

use of org.apache.cassandra.cql3.UntypedResultSet in project cassandra by apache.

the class QueryProcessor method executeAsync.

public static Future<UntypedResultSet> executeAsync(InetAddressAndPort address, String query, Object... values) {
    Prepared prepared = prepareInternal(query);
    QueryOptions options = makeInternalOptions(prepared.statement, values);
    if (prepared.statement instanceof SelectStatement) {
        SelectStatement select = (SelectStatement) prepared.statement;
        int nowInSec = FBUtilities.nowInSeconds();
        ReadQuery readQuery = select.getQuery(options, nowInSec);
        List<ReadCommand> commands;
        if (readQuery instanceof ReadCommand) {
            commands = Collections.singletonList((ReadCommand) readQuery);
        } else if (readQuery instanceof SinglePartitionReadQuery.Group) {
            List<? extends SinglePartitionReadQuery> queries = ((SinglePartitionReadQuery.Group<? extends SinglePartitionReadQuery>) readQuery).queries;
            queries.forEach(a -> {
                if (!(a instanceof ReadCommand))
                    throw new IllegalArgumentException("Queries found which are not ReadCommand: " + a.getClass());
            });
            commands = (List<ReadCommand>) (List<?>) queries;
        } else {
            throw new IllegalArgumentException("Unable to handle; only expected ReadCommands but given " + readQuery.getClass());
        }
        Future<List<Message<ReadResponse>>> future = FutureCombiner.allOf(commands.stream().map(rc -> Message.out(rc.verb(), rc)).map(m -> MessagingService.instance().<ReadResponse>sendWithResult(m, address)).collect(Collectors.toList()));
        ResultSetBuilder result = new ResultSetBuilder(select.getResultMetadata(), select.getSelection().newSelectors(options), null);
        return future.map(list -> {
            int i = 0;
            for (Message<ReadResponse> m : list) {
                ReadResponse rsp = m.payload;
                try (PartitionIterator it = UnfilteredPartitionIterators.filter(rsp.makeIterator(commands.get(i++)), nowInSec)) {
                    while (it.hasNext()) {
                        try (RowIterator partition = it.next()) {
                            select.processPartition(partition, options, result, nowInSec);
                        }
                    }
                }
            }
            return result.build();
        }).map(UntypedResultSet::create);
    }
    throw new IllegalArgumentException("Unable to execute query; only SELECT supported but given: " + query);
}
Also used : ScheduledExecutors(org.apache.cassandra.concurrent.ScheduledExecutors) org.apache.cassandra.cql3.statements(org.apache.cassandra.cql3.statements) LoggerFactory(org.slf4j.LoggerFactory) org.apache.cassandra.db(org.apache.cassandra.db) AbstractType(org.apache.cassandra.db.marshal.AbstractType) org.apache.cassandra.utils(org.apache.cassandra.utils) Global.nanoTime(org.apache.cassandra.utils.Clock.Global.nanoTime) ByteBuffer(java.nio.ByteBuffer) Gossiper(org.apache.cassandra.gms.Gossiper) Function(org.apache.cassandra.cql3.functions.Function) ClientRequestMetrics(org.apache.cassandra.metrics.ClientRequestMetrics) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ENABLE_NODELOCAL_QUERIES(org.apache.cassandra.config.CassandraRelevantProperties.ENABLE_NODELOCAL_QUERIES) FunctionName(org.apache.cassandra.cql3.functions.FunctionName) RowIterator(org.apache.cassandra.db.rows.RowIterator) PartitionIterators(org.apache.cassandra.db.partitions.PartitionIterators) com.google.common.collect(com.google.common.collect) DatabaseDescriptor(org.apache.cassandra.config.DatabaseDescriptor) RequestValidations.checkTrue(org.apache.cassandra.cql3.statements.RequestValidations.checkTrue) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Collectors(java.util.stream.Collectors) QueryPager(org.apache.cassandra.service.pager.QueryPager) Predicate(com.google.common.base.Predicate) org.apache.cassandra.exceptions(org.apache.cassandra.exceptions) Future(org.apache.cassandra.utils.concurrent.Future) PartitionIterator(org.apache.cassandra.db.partitions.PartitionIterator) org.antlr.runtime(org.antlr.runtime) SchemaConstants(org.apache.cassandra.schema.SchemaConstants) org.apache.cassandra.service(org.apache.cassandra.service) InetAddressAndPort(org.apache.cassandra.locator.InetAddressAndPort) java.util(java.util) CQLMetrics(org.apache.cassandra.metrics.CQLMetrics) Message(org.apache.cassandra.net.Message) Cache(com.github.benmanes.caffeine.cache.Cache) ConcurrentMap(java.util.concurrent.ConcurrentMap) Schema(org.apache.cassandra.schema.Schema) SchemaChangeListener(org.apache.cassandra.schema.SchemaChangeListener) ResultSetBuilder(org.apache.cassandra.cql3.selection.ResultSetBuilder) ClientRequestsMetricsHolder(org.apache.cassandra.metrics.ClientRequestsMetricsHolder) ProtocolVersion(org.apache.cassandra.transport.ProtocolVersion) ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) MessagingService(org.apache.cassandra.net.MessagingService) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) FutureCombiner(org.apache.cassandra.utils.concurrent.FutureCombiner) Logger(org.slf4j.Logger) Tracing(org.apache.cassandra.tracing.Tracing) Ints(com.google.common.primitives.Ints) TimeUnit(java.util.concurrent.TimeUnit) UnfilteredPartitionIterators(org.apache.cassandra.db.partitions.UnfilteredPartitionIterators) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ImmediateExecutor(org.apache.cassandra.concurrent.ImmediateExecutor) ResultSetBuilder(org.apache.cassandra.cql3.selection.ResultSetBuilder) Message(org.apache.cassandra.net.Message) ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) PartitionIterator(org.apache.cassandra.db.partitions.PartitionIterator) RowIterator(org.apache.cassandra.db.rows.RowIterator)

Example 73 with UntypedResultSet

use of org.apache.cassandra.cql3.UntypedResultSet in project cassandra by apache.

the class AggregationTest method testAggregateWithWriteTimeOrTTL.

@Test
public void testAggregateWithWriteTimeOrTTL() throws Throwable {
    createTable("CREATE TABLE %s (a int primary key, b int, c int)");
    // Test with empty table
    assertColumnNames(execute("SELECT count(writetime(b)), min(ttl(b)) as min, writetime(b), ttl(c) as first FROM %s"), "system.count(writetime(b))", "min", "writetime(b)", "first");
    assertRows(execute("SELECT count(writetime(b)), min(ttl(b)) as min, writetime(b), ttl(c) as first FROM %s"), row(0L, null, null, null));
    long today = System.currentTimeMillis() * 1000;
    long yesterday = today - (DateUtils.MILLIS_PER_DAY * 1000);
    final int secondsPerMinute = 60;
    execute("INSERT INTO %s (a, b, c) VALUES (1, 2, null) USING TTL " + (20 * secondsPerMinute));
    execute("INSERT INTO %s (a, b, c) VALUES (2, 4, 6) USING TTL " + (10 * secondsPerMinute));
    execute("INSERT INTO %s (a, b, c) VALUES (4, 8, 12) USING TIMESTAMP " + yesterday);
    assertRows(execute("SELECT count(writetime(b)), count(ttl(b)) FROM %s"), row(3L, 2L));
    UntypedResultSet resultSet = execute("SELECT min(ttl(b)), ttl(b) FROM %s");
    assertEquals(1, resultSet.size());
    Row row = resultSet.one();
    assertTrue(row.getInt("ttl(b)") > (10 * secondsPerMinute));
    assertTrue(row.getInt("system.min(ttl(b))") <= (10 * secondsPerMinute));
    resultSet = execute("SELECT min(writetime(b)), writetime(b) FROM %s");
    assertEquals(1, resultSet.size());
    row = resultSet.one();
    assertTrue(row.getLong("writetime(b)") >= today);
    assertTrue(row.getLong("system.min(writetime(b))") == yesterday);
}
Also used : UntypedResultSet(org.apache.cassandra.cql3.UntypedResultSet) Row(org.apache.cassandra.cql3.UntypedResultSet.Row) Test(org.junit.Test)

Example 74 with UntypedResultSet

use of org.apache.cassandra.cql3.UntypedResultSet in project cassandra by apache.

the class InsertTest method testInsertWithDefaultTtl.

@Test
public void testInsertWithDefaultTtl() throws Throwable {
    final int secondsPerMinute = 60;
    createTable("CREATE TABLE %s (a int PRIMARY KEY, b int) WITH default_time_to_live = " + (10 * secondsPerMinute));
    execute("INSERT INTO %s (a, b) VALUES (1, 1)");
    UntypedResultSet resultSet = execute("SELECT ttl(b) FROM %s WHERE a = 1");
    Assert.assertEquals(1, resultSet.size());
    Row row = resultSet.one();
    Assert.assertTrue(row.getInt("ttl(b)") >= (9 * secondsPerMinute));
    execute("INSERT INTO %s (a, b) VALUES (2, 2) USING TTL ?", (5 * secondsPerMinute));
    resultSet = execute("SELECT ttl(b) FROM %s WHERE a = 2");
    Assert.assertEquals(1, resultSet.size());
    row = resultSet.one();
    Assert.assertTrue(row.getInt("ttl(b)") <= (5 * secondsPerMinute));
    execute("INSERT INTO %s (a, b) VALUES (3, 3) USING TTL ?", 0);
    assertRows(execute("SELECT ttl(b) FROM %s WHERE a = 3"), row(new Object[] { null }));
    execute("INSERT INTO %s (a, b) VALUES (4, 4) USING TTL ?", unset());
    resultSet = execute("SELECT ttl(b) FROM %s WHERE a = 4");
    Assert.assertEquals(1, resultSet.size());
    row = resultSet.one();
    Assert.assertTrue(row.getInt("ttl(b)") >= (9 * secondsPerMinute));
    execute("INSERT INTO %s (a, b) VALUES (?, ?) USING TTL ?", 4, 4, null);
    assertRows(execute("SELECT ttl(b) FROM %s WHERE a = 4"), row(new Object[] { null }));
}
Also used : UntypedResultSet(org.apache.cassandra.cql3.UntypedResultSet) Row(org.apache.cassandra.cql3.UntypedResultSet.Row) Test(org.junit.Test)

Example 75 with UntypedResultSet

use of org.apache.cassandra.cql3.UntypedResultSet in project cassandra by apache.

the class SelectTest method testSelectWithAlias.

/**
 * Migrated from cql_tests.py:TestCQL.select_with_alias_test()
 */
@Test
public void testSelectWithAlias() throws Throwable {
    createTable("CREATE TABLE %s (id int PRIMARY KEY, name text)");
    for (int id = 0; id < 5; id++) execute("INSERT INTO %s (id, name) VALUES (?, ?) USING TTL 10 AND TIMESTAMP 0", id, "name" + id);
    // test aliasing count( *)
    UntypedResultSet rs = execute("SELECT count(*) AS user_count FROM %s");
    assertEquals("user_count", rs.metadata().get(0).name.toString());
    assertEquals(5L, rs.one().getLong(rs.metadata().get(0).name.toString()));
    // test aliasing regular value
    rs = execute("SELECT name AS user_name FROM %s WHERE id = 0");
    assertEquals("user_name", rs.metadata().get(0).name.toString());
    assertEquals("name0", rs.one().getString(rs.metadata().get(0).name.toString()));
    // test aliasing writetime
    rs = execute("SELECT writeTime(name) AS name_writetime FROM %s WHERE id = 0");
    assertEquals("name_writetime", rs.metadata().get(0).name.toString());
    assertEquals(0, rs.one().getInt(rs.metadata().get(0).name.toString()));
    // test aliasing ttl
    rs = execute("SELECT ttl(name) AS name_ttl FROM %s WHERE id = 0");
    assertEquals("name_ttl", rs.metadata().get(0).name.toString());
    int ttl = rs.one().getInt(rs.metadata().get(0).name.toString());
    assertTrue(ttl == 9 || ttl == 10);
    // test aliasing a regular function
    rs = execute("SELECT intAsBlob(id) AS id_blob FROM %s WHERE id = 0");
    assertEquals("id_blob", rs.metadata().get(0).name.toString());
    assertEquals(ByteBuffer.wrap(new byte[4]), rs.one().getBlob(rs.metadata().get(0).name.toString()));
    // test that select throws a meaningful exception for aliases in where clause
    assertInvalidMessage("Undefined column name user_id", "SELECT id AS user_id, name AS user_name FROM %s WHERE user_id = 0");
    // test that select throws a meaningful exception for aliases in order by clause
    assertInvalidMessage("Undefined column name user_name", "SELECT id AS user_id, name AS user_name FROM %s WHERE id IN (0) ORDER BY user_name");
}
Also used : UntypedResultSet(org.apache.cassandra.cql3.UntypedResultSet) Test(org.junit.Test)

Aggregations

UntypedResultSet (org.apache.cassandra.cql3.UntypedResultSet)107 Test (org.junit.Test)35 UUID (java.util.UUID)8 ByteBuffer (java.nio.ByteBuffer)6 ColumnFamilyStore (org.apache.cassandra.db.ColumnFamilyStore)6 InetAddressAndPort (org.apache.cassandra.locator.InetAddressAndPort)6 HashSet (java.util.HashSet)5 Mutation (org.apache.cassandra.db.Mutation)5 VisibleForTesting (com.google.common.annotations.VisibleForTesting)4 HashMap (java.util.HashMap)4 RowUpdateBuilder (org.apache.cassandra.db.RowUpdateBuilder)4 TableMetadata (org.apache.cassandra.schema.TableMetadata)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 ImmutableSet (com.google.common.collect.ImmutableSet)3 SSTableReader (org.apache.cassandra.io.sstable.format.SSTableReader)3 ResultMessage (org.apache.cassandra.transport.messages.ResultMessage)3 Predicate (com.google.common.base.Predicate)2 IOException (java.io.IOException)2 InetAddress (java.net.InetAddress)2 ArrayList (java.util.ArrayList)2