selectBuilder = QueryBuilder.select().all(); } else { selectBuilder = QueryBuilder.select(); for (String col : fields) { ((Select.Selection) selectBuilder).column(col); scanStmt.append(QueryBuilder.bindMarker()); stmt = session.prepare(scanStmt.toString()); stmt.setConsistencyLevel(readConsistencyLevel); if (trace) { stmt.enableTracing(); logger.debug(stmt.getQueryString()); logger.debug("startKey = {}, recordcount = {}", startkey, recordcount); ResultSet rs = session.execute(stmt.bind(startkey, Integer.valueOf(recordcount))); while (!rs.isExhausted()) { Row row = rs.one(); tuple = new HashMap<String, ByteIterator>(); ColumnDefinitions cd = row.getColumnDefinitions(); ByteBuffer val = row.getBytesUnsafe(def.getName()); if (val != null) { tuple.put(def.getName(), new ByteArrayByteIterator(val.array()));
@Override public MapKeyResults getAllKeys(final MapScope scope, final String cursor, final int limit ){ final int[] buckets = BUCKET_LOCATOR.getAllBuckets( scope.getName() ); final List<ByteBuffer> partitionKeys = new ArrayList<>(NUM_BUCKETS.length); for (int bucket : buckets) { partitionKeys.add(getMapKeyPartitionKey(scope, bucket)); } Clause in = QueryBuilder.in("key", partitionKeys); Statement statement; if( isBlank(cursor) ){ statement = QueryBuilder.select().all().from(MAP_KEYS_TABLE) .where(in) .setFetchSize(limit); }else{ statement = QueryBuilder.select().all().from(MAP_KEYS_TABLE) .where(in) .setFetchSize(limit) .setPagingState(PagingState.fromString(cursor)); } ResultSet resultSet = session.execute(statement); PagingState pagingState = resultSet.getExecutionInfo().getPagingState(); final List<String> keys = new ArrayList<>(); Iterator<Row> resultIterator = resultSet.iterator(); int size = 0; while( resultIterator.hasNext() && size < limit){ size++; keys.add((String)DataType.text().deserialize(resultIterator.next().getBytes("column1"), ProtocolVersion.NEWEST_SUPPORTED)); } return new MapKeyResults(pagingState != null ? pagingState.toString() : null, keys); }
@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(); }
@Override public boolean advanceNextPosition() { if (!rs.isExhausted()) { currentRow = rs.one(); count++; return true; } return false; }
if (iterator.getColumnDefinitions().contains("row_time")) newIndex = true; while (!iterator.isExhausted()) Row record = iterator.one(); if (record.getString(1) == null) continue; //empty row rowKey = new DataPointsRowKey(m_metricName, m_clusterName, record.getTimestamp(0).getTime(), record.getString(1), new TreeMap<String, String>(record.getMap(2, String.class, String.class)));
@Override public Result<TransferLog> getAllTransferLogs(PagingState pagingState, int fetchSize ) { Statement query = QueryBuilder.select().all().from(TABLE_TRANSFER_LOG); ResultSet rs = cassandraClient.getApplicationSession().execute( query ); final PagingState newPagingState = rs.getExecutionInfo().getPagingState(); int numReturned = rs.getAvailableWithoutFetching(); for ( int i=0; i<numReturned; i++ ) { Row row = rs.one(); TransferLog tlog = new TransferLog( row.getString( COLUMN_QUEUE_NAME ), row.getString( COLUMN_SOURCE_REGION ), row.getString( COLUMN_DEST_REGION ), row.getUUID( COLUMN_MESSAGE_ID ), row.getLong( COLUMN_TRANSFER_TIME ));
@Test(groups = "short") public void should_use_collection_codecs_with_prepared_statements_1() { session() .execute( session() .prepare(insertQuery) .bind(n_int, l_int, l_bigint, s_float, s_double, m_varint, m_decimal)); PreparedStatement ps = session().prepare(selectQuery); ResultSet rows = session().execute(ps.bind(n_int)); Row row = rows.one(); assertRow(row); }
@Test(groups = "short") public void should_use_statement_timestamp_over_generator() { timestampFromGenerator = 10; String query = "INSERT INTO foo (k, v) VALUES (1, 1)"; session().execute(new SimpleStatement(query).setDefaultTimestamp(30)); long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0); assertEquals(writeTime, 30); }
@Test(groups = "short") public void should_delete_list_element_with_bind_marker() throws Exception { // given session().execute("INSERT INTO test_coll (k, a) VALUES (1, [1,2,3])"); // when BuiltStatement statement = delete().listElt("a", bindMarker()).from("test_coll").where(eq("k", 1)); PreparedStatement ps = session().prepare(statement); session().execute(ps.bind(1)); // then List<Integer> actual = session().execute("SELECT a FROM test_coll WHERE k = 1").one().getList("a", Integer.class); assertThat(actual).containsExactly(1, 3); }
@Test(groups = "short") public void should_set_flag_on_successful_agreement() { ProtocolOptions protocolOptions = cluster().getConfiguration().getProtocolOptions(); protocolOptions.maxSchemaAgreementWaitSeconds = 10; ResultSet rs = session().execute(String.format(CREATE_TABLE, COUNTER.getAndIncrement())); assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue(); }
@Test(groups = "short") public void should_encode_null_values() throws Exception { Map<String, ByteBuffer> payload = new HashMap<String, ByteBuffer>(); payload.put("k1", Statement.NULL_PAYLOAD_VALUE); Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1); statement.setOutgoingPayload(payload); ResultSet rows = session().execute(statement); Map<String, ByteBuffer> actual = rows.getExecutionInfo().getIncomingPayload(); assertThat(actual).isEqualTo(payload); }
@Test(groups = "short") public void should_update_statement_id_when_metadata_changed_across_executions() { // given PreparedStatement ps = session().prepare("SELECT * FROM prepared_statement_invalidation_test WHERE a = ?"); MD5Digest idBefore = ps.getPreparedId().resultSetMetadata.id; // when session().execute("ALTER TABLE prepared_statement_invalidation_test ADD d int"); BoundStatement bs = ps.bind(1); ResultSet rows = session().execute(bs); // then MD5Digest idAfter = ps.getPreparedId().resultSetMetadata.id; assertThat(idBefore).isNotEqualTo(idAfter); assertThat(ps.getPreparedId().resultSetMetadata.variables) .hasSize(4) .containsVariable("d", DataType.cint()); assertThat(bs.preparedStatement().getPreparedId().resultSetMetadata.variables) .hasSize(4) .containsVariable("d", DataType.cint()); assertThat(rows.getColumnDefinitions()).hasSize(4).containsVariable("d", DataType.cint()); }
@Test(groups = "short") @CassandraVersion(value = "3.6", description = "Non-frozen UDTs were introduced in C* 3.6") public void should_indicate_user_type_is_not_frozen() { session().execute("CREATE TABLE not_frozen_table(k int primary key, v type_for_frozen_test)"); KeyspaceMetadata keyspaceMetadata = cluster().getMetadata().getKeyspace(this.keyspace); assertThat(keyspaceMetadata.getUserType("type_for_frozen_test")).isNotFrozen(); DataType userType = keyspaceMetadata.getTable("not_frozen_table").getColumn("v").getType(); assertThat(userType).isNotFrozen(); assertThat(userType.toString()).isEqualTo(keyspace + ".type_for_frozen_test"); ResultSet rs = session().execute("SELECT v FROM not_frozen_table WHERE k = 1"); assertThat(rs.getColumnDefinitions().getType(0)).isNotFrozen(); PreparedStatement pst = session().prepare("SELECT v FROM not_frozen_table WHERE k = ?"); assertThat(pst.getVariables().getType(0)).isNotFrozen(); } }
@CassandraVersion("2.0.0") @Test(groups = "short") public void should_execute_wrapped_simple_statement() { session().execute(new CustomStatement(new SimpleStatement(INSERT_QUERY, "key_simple", 1))); ResultSet rs = session().execute(new CustomStatement(new SimpleStatement(SELECT_QUERY, "key_simple"))); assertThat(rs.one().getInt("v")).isEqualTo(1); }
@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 should_update_statement_id_when_metadata_changed_across_pages() throws Exception { PreparedStatement ps = session().prepare("SELECT * FROM prepared_statement_invalidation_test"); ResultSet rows = session().execute(ps.bind().setFetchSize(2)); assertThat(rows.isFullyFetched()).isFalse(); MD5Digest idBefore = ps.getPreparedId().resultSetMetadata.id; ColumnDefinitions definitionsBefore = rows.getColumnDefinitions(); assertThat(definitionsBefore).hasSize(3).doesNotContainVariable("d"); int remaining = rows.getAvailableWithoutFetching(); while (remaining-- > 0) { try { rows.one().getInt("d"); fail("expected an error"); } catch (IllegalArgumentException e) { session().execute("ALTER TABLE prepared_statement_invalidation_test ADD d int"); assertThat(row.isNull("d")).isTrue(); MD5Digest idAfter = ps.getPreparedId().resultSetMetadata.id; ColumnDefinitions definitionsAfter = rows.getColumnDefinitions(); assertThat(idBefore).isNotEqualTo(idAfter); assertThat(definitionsAfter).hasSize(4).containsVariable("d", DataType.cint());
@Test(groups = "short") public void insertUdtTest() throws Exception { UserType udtType = cluster().getMetadata().getKeyspace(keyspace).getUserType("udt"); UDTValue udtValue = udtType.newValue().setInt("i", 2).setInet("a", InetAddress.getByName("localhost")); Statement insert = insertInto("udtTest").value("k", 1).value("t", udtValue); assertEquals(insert.toString(), "INSERT INTO udtTest (k,t) 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(); assertEquals(rows.size(), 1); Row r1 = rows.get(0); assertEquals("127.0.0.1", r1.getUDTValue("t").getInet("a").getHostAddress()); }
@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); }
@Test(groups = "short") public void dateHandlingTest() throws Exception { Date d = new Date(); session().execute(insertInto("dateTest").value("t", d)); String query = select().from("dateTest").where(eq(token("t"), fcall("token", d))).toString(); List<Row> rows = session().execute(query).all(); assertEquals(1, rows.size()); Row r1 = rows.get(0); assertEquals(d, r1.getTimestamp("t")); }
@Test(groups = "short") @CassandraVersion(value = "2.0.0") public void should_reuse_wrapped_bound_statement_for_multipage_query() { loadBalancingPolicy.customStatementsHandled.set(0); for (int v = 1; v <= 100; v++) session().execute(new SimpleStatement(INSERT_MULTIPAGE_QUERY, "key_prepared_multipage", v)); PreparedStatement ps = session().prepare(SELECT_MULTIPAGE_QUERY); BoundStatement bs = ps.bind("key_prepared_multipage"); bs.setFetchSize(1); CustomStatement customStatement = new CustomStatement(bs); ResultSet rs = session().execute(customStatement); assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(1); Iterator<Row> it = rs.iterator(); assertThat(it.hasNext()).isTrue(); it.next(); assertThat(rs.getExecutionInfo().getStatement()).isEqualTo(customStatement); assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(1); assertThat(it.hasNext()).isTrue(); it.next(); assertThat(rs.getExecutionInfo().getStatement()).isEqualTo(customStatement); assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(2); }