@Override public List<SizeEstimate> getSizeEstimates(String keyspaceName, String tableName) { checkSizeEstimatesTableExist(); Statement statement = select("range_start", "range_end", "mean_partition_size", "partitions_count") .from(SYSTEM, SIZE_ESTIMATES) .where(eq("keyspace_name", keyspaceName)) .and(eq("table_name", tableName)); ResultSet result = executeWithSession(session -> session.execute(statement)); ImmutableList.Builder<SizeEstimate> estimates = ImmutableList.builder(); for (Row row : result.all()) { SizeEstimate estimate = new SizeEstimate( row.getString("range_start"), row.getString("range_end"), row.getLong("mean_partition_size"), row.getLong("partitions_count")); estimates.add(estimate); } return estimates.build(); }
if (row.isNull(i)) { return null; case TEXT: case VARCHAR: return CassandraCqlUtils.quoteStringLiteral(row.getString(i)); case INT: return Integer.toString(row.getInt(i)); case BIGINT: case COUNTER: return Long.toString(row.getLong(i)); case BOOLEAN: return Boolean.toString(row.getBool(i)); case DOUBLE: return Double.toString(row.getDouble(i)); case FLOAT: return Float.toString(row.getFloat(i)); case DECIMAL: return row.getDecimal(i).toString(); case UUID: case TIMEUUID: return row.getUUID(i).toString(); case TIMESTAMP: return Long.toString(row.getTimestamp(i).getTime()); case INET: return CassandraCqlUtils.quoteStringLiteral(toAddrString(row.getInet(i))); case VARINT: return row.getVarint(i).toString(); case BLOB:
@Override public DatabaseQueueMessageBody loadMessageData(final UUID messageId ){ logger.trace("loadMessageData {}", messageId); Clause messageIdClause = QueryBuilder.eq( COLUMN_MESSAGE_ID, messageId ); Statement select = QueryBuilder.select().from( TABLE_MESSAGE_DATA).where(messageIdClause); Row row = cassandraClient.getApplicationSession().execute(select).one(); if ( row == null ) { return null; } return new DatabaseQueueMessageBody( row.getBytes( COLUMN_MESSAGE_DATA), row.getString( COLUMN_CONTENT_TYPE)); }
@Override public long getLong(int i) { switch (getCassandraType(i)) { case INT: return currentRow.getInt(i); case BIGINT: case COUNTER: return currentRow.getLong(i); case TIMESTAMP: return currentRow.getTimestamp(i).getTime(); case FLOAT: return floatToRawIntBits(currentRow.getFloat(i)); default: throw new IllegalStateException("Cannot retrieve long for " + getCassandraType(i)); } }
private Iterator<Shard> getIteratorFromRows( List<Row> rows){ List<Shard> shards = new ArrayList<>(rows.size()); rows.forEach(row -> { final String queueName = row.getString( ShardSerializationImpl.COLUMN_QUEUE_NAME); final String region = row.getString( ShardSerializationImpl.COLUMN_REGION); final long shardId = row.getLong( ShardSerializationImpl.COLUMN_SHARD_ID); final UUID pointer = row.getUUID( ShardSerializationImpl.COLUMN_POINTER); shards.add(new Shard(queueName, region, shardType, shardId, pointer)); nextStart = shardId; }); return shards.iterator(); }
@Test(groups = "short") public void should_handle_contains_on_list_with_index() { PreparedStatement byBuyer = session() .prepare( select("id", "description", "buyers") .from("products") .where(contains("buyers", bindMarker("buyer")))); ResultSet results = session().execute(byBuyer.bind().setInt("buyer", 4)); Row row = results.one(); assertThat(row).isNotNull(); assertThat(row.getInt("id")).isEqualTo(38471); assertThat(row.getList("buyers", Integer.class)).contains(4); }
@Test(groups = "short") public void textRoutingKeyTest() throws Exception { BuiltStatement query; TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT); assertNotNull(table); ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion(); CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE; String txt = "If she weighs the same as a duck... she's made of wood."; query = insertInto(table).values(new String[] {"k", "a", "b"}, new Object[] {txt, 1, 2}); assertEquals( query.getRoutingKey(protocolVersion, codecRegistry), ByteBuffer.wrap(txt.getBytes())); session().execute(query); query = select().from(table).where(eq("k", txt)); assertEquals( query.getRoutingKey(protocolVersion, codecRegistry), ByteBuffer.wrap(txt.getBytes())); Row row = session().execute(query).one(); assertEquals(row.getString("k"), txt); assertEquals(row.getInt("a"), 1); assertEquals(row.getInt("b"), 2); }
@Test(groups = "short") public void should_use_generator_timestamp_if_none_other_specified() { timestampFromGenerator = 10; String query = "INSERT INTO foo (k, v) VALUES (1, 1)"; session().execute(query); long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0); assertEquals(writeTime, 10); }
@Test(groups = "short") public void should_delete_set_element_with_bind_marker() throws Exception { // given session().execute("INSERT INTO test_coll (k, c) VALUES (1, {'foo','bar','qix'})"); // when BuiltStatement statement = delete().setElt("c", bindMarker()).from("test_coll").where(eq("k", 1)); PreparedStatement ps = session().prepare(statement); session().execute(ps.bind("foo")); // then Set<String> actual = session().execute("SELECT c FROM test_coll WHERE k = 1").one().getSet("c", String.class); assertThat(actual).containsOnly("bar", "qix"); }
@Test(groups = "short") public void should_execute_wrapped_bound_statement() { PreparedStatement preparedStatement = session().prepare(new SimpleStatement(INSERT_QUERY)); session().execute(new CustomStatement(preparedStatement.bind("key_bound", 1))); preparedStatement = session().prepare(new SimpleStatement(SELECT_QUERY)); ResultSet rs = session().execute(new CustomStatement(preparedStatement.bind("key_bound"))); assertThat(rs.one().getInt("v")).isEqualTo(1); }
@CassandraVersion("2.0.0") @Test(groups = "short") public void should_execute_wrapped_batch_statement() { BatchStatement batchStatement = new BatchStatement(); batchStatement.add(new SimpleStatement(INSERT_QUERY, "key_batch", 1)); session().execute(new CustomStatement(batchStatement)); ResultSet rs = session().execute(SELECT_QUERY, "key_batch"); assertThat(rs.one().getInt("v")).isEqualTo(1); }
@Test(groups = "short") public void simpleBatchTest() { try { PreparedStatement st = session().prepare("INSERT INTO test (k, v) VALUES (?, ?)"); BatchStatement batch = new BatchStatement(); batch.add(new SimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0)); batch.add(st.bind("key1", 1)); batch.add(st.bind("key2", 0)); assertEquals(3, batch.size()); session().execute(batch); ResultSet rs = session().execute("SELECT * FROM test"); Row r; r = rs.one(); assertEquals(r.getString("k"), "key1"); assertEquals(r.getInt("v"), 0); r = rs.one(); assertEquals(r.getString("k"), "key1"); assertEquals(r.getInt("v"), 1); r = rs.one(); assertEquals(r.getString("k"), "key2"); assertEquals(r.getInt("v"), 0); assertTrue(rs.isExhausted()); } catch (UnsupportedFeatureException e) { // This is expected when testing the protocol v1 assertEquals( cluster().getConfiguration().getProtocolOptions().getProtocolVersion(), ProtocolVersion.V1); } }
@Test(groups = "short") public void should_handle_collections_of_UDT() throws Exception { UserType udtType = cluster().getMetadata().getKeyspace(keyspace).getUserType("udt"); UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost")); UDTValue udtValue2 = udtType.newValue().setInt("i", 3).setInet("a", InetAddress.getByName("localhost")); Statement insert = insertInto("udtTest").value("k", 1).value("l", ImmutableList.of(udtValue)); assertThat(insert.toString()) .isEqualTo("INSERT INTO udtTest (k,l) VALUES (1,[{i:2,a:'127.0.0.1'}]);"); session().execute(insert); List<Row> rows = session().execute(select().from("udtTest").where(eq("k", 1))).all(); assertThat(rows.size()).isEqualTo(1); Row r1 = rows.get(0); assertThat(r1.getList("l", UDTValue.class).get(0).getInet("a").getHostAddress()) .isEqualTo("127.0.0.1"); Map<Integer, UDTValue> map = Maps.newHashMap(); map.put(0, udtValue); map.put(2, udtValue2); Statement updateMap = update("udtTest").with(putAll("m", map)).where(eq("k", 1)); assertThat(updateMap.toString()) .isEqualTo( "UPDATE udtTest SET m=m+{0:{i:2,a:'127.0.0.1'},2:{i:3,a:'127.0.0.1'}} WHERE k=1;"); session().execute(updateMap); rows = session().execute(select().from("udtTest").where(eq("k", 1))).all(); r1 = rows.get(0); assertThat(r1.getMap("m", Integer.class, UDTValue.class)).isEqualTo(map); }
@Test(groups = "short") public void should_init_cluster_and_session_if_needed() throws Exception { // For this test we need an uninitialized cluster, so we can't reuse the one provided by the // parent class. Rebuild a new one with the same (unique) host. Host host = cluster().getMetadata().allHosts().iterator().next(); Cluster cluster2 = register( Cluster.builder() .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress())) .build()); try { Session session2 = cluster2.newSession(); // Neither cluster2 nor session2 are initialized at this point assertThat(cluster2.manager.metadata).isNull(); ResultSetFuture future = session2.executeAsync("select release_version from system.local"); Row row = Uninterruptibles.getUninterruptibly(future).one(); assertThat(row.getString(0)).isNotEmpty(); } finally { cluster2.close(); } }
byName.setSet("s", set, TypeTokens.listOf(mapping.javaType)); session().execute(byName); Row row = session().execute(select.bind(key)).one(); assertThat(getValue(row, "v", mapping.outerType, registry)).isEqualTo(mapping.value); assertThat(row.getList("l", mapping.codec.getJavaType())).isEqualTo(list); assertThat(row.getMap("m", mapping.codec.getJavaType(), mapping.codec.getJavaType())) .isEqualTo(map); TupleValue returnedTuple = row.getTupleValue("t"); assertThat(getValue(returnedTuple, 0, mapping.outerType, registry)) .isEqualTo(mapping.value); .isEqualTo(mapping.value); assertThat(row.getSet("s", TypeTokens.listOf(mapping.javaType))).isEqualTo(set); assertThat(row.getList(1, mapping.codec.getJavaType())).isEqualTo(list); assertThat(row.getMap(2, mapping.codec.getJavaType(), mapping.codec.getJavaType())) .isEqualTo(map); TupleValue returnedTuple = row.getTupleValue(3); assertThat(getValue(returnedTuple, 0, mapping.outerType, registry)) .isEqualTo(mapping.value); assertThat(row.getSet(4, TypeTokens.listOf(mapping.javaType))).isEqualTo(set);
@Test(groups = "short") public void should_check_agreement_through_cluster_metadata() { Cluster controlCluster = register(TestUtils.buildControlCluster(cluster(), ccm())); Session controlSession = controlCluster.connect(); Row localRow = controlSession.execute("SELECT schema_version FROM system.local").one(); UUID localVersion = localRow.getUUID("schema_version"); Row peerRow = controlSession.execute("SELECT peer, schema_version FROM system.peers").one(); InetAddress peerAddress = peerRow.getInet("peer"); UUID peerVersion = peerRow.getUUID("schema_version"); // The two nodes should be in agreement at this point, but check just in case: assertThat(localVersion).isEqualTo(peerVersion); // Now check the method under test: assertThat(cluster().getMetadata().checkSchemaAgreement()).isTrue(); // Insert a fake version to simulate a disagreement: forceSchemaVersion(controlSession, peerAddress, UUIDs.random()); assertThat(cluster().getMetadata().checkSchemaAgreement()).isFalse(); forceSchemaVersion(controlSession, peerAddress, peerVersion); }
@Test(groups = "short") public void batchTest() throws Exception { try { PreparedStatement ps1 = session().prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, ?)"); PreparedStatement ps2 = session().prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, 'bar')"); BatchStatement bs = new BatchStatement(); bs.add(ps1.bind("one", "foo")); bs.add(ps2.bind("two")); bs.add( new SimpleStatement( "INSERT INTO " + SIMPLE_TABLE2 + " (k, v) VALUES ('three', 'foobar')")); session().execute(bs); List<Row> all = session().execute("SELECT * FROM " + SIMPLE_TABLE2).all(); assertEquals("three", all.get(0).getString("k")); assertEquals("foobar", all.get(0).getString("v")); assertEquals("one", all.get(1).getString("k")); assertEquals("foo", all.get(1).getString("v")); assertEquals("two", all.get(2).getString("k")); assertEquals("bar", all.get(2).getString("v")); } catch (UnsupportedFeatureException e) { // This is expected when testing the protocol v1 if (cluster().getConfiguration().getProtocolOptions().getProtocolVersion() != ProtocolVersion.V1) throw e; } }
@Test(groups = "short") public void should_handle_contains_on_set_with_index() { PreparedStatement byCategory = session() .prepare( select("id", "description", "categories") .from("products") .where(contains("categories", bindMarker("category")))); ResultSet results = session().execute(byCategory.bind().setString("category", "hdtv")); assertThat(results.getAvailableWithoutFetching()).isEqualTo(2); for (Row row : results) { assertThat(row.getSet("categories", String.class)).contains("hdtv"); } }
@Test(groups = "short") @CassandraVersion( value = "2.0.9", description = "This will only work with C* 2.0.9 (CASSANDRA-7337)") public void casBatchTest() { PreparedStatement st = session().prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS"); BatchStatement batch = new BatchStatement(); batch.add(new SimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0)); batch.add(st.bind("key1", 1)); batch.add(st.bind("key1", 2)); assertEquals(3, batch.size()); ResultSet rs = session().execute(batch); Row r = rs.one(); assertTrue(!r.isNull("[applied]")); assertEquals(r.getBool("[applied]"), true); rs = session().execute(batch); r = rs.one(); assertTrue(!r.isNull("[applied]")); assertEquals(r.getBool("[applied]"), false); } }
@Test(groups = "short") @CassandraVersion("3.2") public void should_support_fcall_on_cast_column() { .execute( select() .fcall("avg", cast(column("i"), DataType.cfloat())) .as("iavg") .from(TABLE2) .where(eq("k", "cast_t"))); assertThat(ar.getAvailableWithoutFetching()).isEqualTo(1); Row row = ar.one(); assertThat(row.getColumnDefinitions().getType("iavg")).isEqualTo(DataType.cfloat()); Float f = row.getFloat("iavg");