Refine search
stmt = session.prepare(insertStmt); stmt.setConsistencyLevel(writeConsistencyLevel); if (trace) { stmt.enableTracing(); logger.debug(stmt.getQueryString()); logger.debug("key = {}", key); for (Map.Entry<String, ByteIterator> entry : values.entrySet()) { BoundStatement boundStmt = stmt.bind().setString(0, key); ColumnDefinitions vars = stmt.getVariables(); for (int i = 1; i < vars.size(); i++) { boundStmt.setString(i, values.get(vars.getName(i)).toString()); session.execute(boundStmt);
final String paramValue, final String paramType) throws IllegalArgumentException { if (paramValue == null) { statement.setToNull(paramIndex); return; } else if (paramType == null) { statement.setString(paramIndex, paramValue); statement.setBool(paramIndex, (boolean) typeCodec.parse(paramValue)); statement.setInt(paramIndex, (int) typeCodec.parse(paramValue)); statement.setLong(paramIndex, (long) typeCodec.parse(paramValue)); statement.setFloat(paramIndex, (float) typeCodec.parse(paramValue)); statement.setDouble(paramIndex, (double) typeCodec.parse(paramValue)); statement.setBytes(paramIndex, (ByteBuffer) typeCodec.parse(paramValue)); statement.setTimestamp(paramIndex, (Date) typeCodec.parse(paramValue)); DataType secondParamType = getPrimitiveDataTypeFromString(secondParamTypeName); DataType mapType = DataType.map(firstParamType, secondParamType); statement.setMap(paramIndex, (Map) codecRegistry.codecFor(mapType).parse(paramValue)); return; statement.setSet(paramIndex, (Set) codecRegistry.codecFor(setType).parse(paramValue)); return;
@Override public Iterable<String> listKeys(String service, String serviceKey, String keyStartsWith) throws DatastoreException { String begin = keyStartsWith; String end = keyStartsWith + Character.MAX_VALUE; List<String> ret = new ArrayList<>(); BoundStatement statement = new BoundStatement(m_metaCluster.psServiceIndexListKeysPrefix); statement.setString(0, service); statement.setString(1, serviceKey); statement.setString(2, begin); statement.setString(3, end); statement.setConsistencyLevel(m_metaCluster.getReadConsistencyLevel()); ResultSet resultSet = m_metaCluster.execute(statement); while (!resultSet.isExhausted()) { String key = resultSet.one().getString(0); if (key != null) { // The last row for the primary key doesn't get deleted and has a null key and isExhausted still return false. So check for null ret.add(key); } } return ret; }
@Override public void setValue(String service, String serviceKey, String key, String value) throws DatastoreException { BoundStatement statement = new BoundStatement(m_metaCluster.psServiceIndexInsert); statement.setString(0, service); statement.setString(1, serviceKey); statement.setString(2, key); statement.setString(3, value); statement.setConsistencyLevel(m_metaCluster.getWriteConsistencyLevel()); m_metaCluster.execute(statement); }
public void addMetricName(String metricName) { m_newMetrics.add(metricName); BoundStatement bs = new BoundStatement(m_clusterConnection.psStringIndexInsert); bs.setBytesUnsafe(0, ByteBuffer.wrap(ROW_KEY_METRIC_NAMES.getBytes(UTF_8))); bs.setString(1, metricName); bs.setConsistencyLevel(m_consistencyLevel); metricNamesBatch.add(bs); }
public void deleteDataPoint(DataPointsRowKey rowKey, int columnTime) throws IOException { BoundStatement boundStatement = new BoundStatement(m_clusterConnection.psDataPointsDelete); boundStatement.setBytesUnsafe(0, DATA_POINTS_ROW_KEY_SERIALIZER.toByteBuffer(rowKey)); ByteBuffer b = ByteBuffer.allocate(4); b.putInt(columnTime); b.rewind(); boundStatement.setBytesUnsafe(1, b); boundStatement.setConsistencyLevel(m_consistencyLevel); boundStatement.setIdempotent(true); addBoundStatement(boundStatement); }
@Test(groups = "short") public void should_use_default_codecs_with_prepared_statements_3() { session() .execute( session() .prepare(insertQuery) .bind() .set(0, n_int, Integer.class) .set(1, n_bigint, Long.class) .set(2, n_float, Float.class) .set(3, n_double, Double.class) .set(4, n_varint, BigInteger.class) .set(5, n_decimal, BigDecimal.class)); PreparedStatement ps = session().prepare(selectQuery); ResultSet rows = session().execute(ps.bind().setInt(0, n_int).setLong(1, n_bigint)); Row row = rows.one(); assertRow(row); }
@Test(groups = "short") public void should_work_with_prepared_statements_2() { session() .execute( session() .prepare(insertQuery) .bind() .setInt(0, pk) .setList(1, v, elementsType) // variant with element type explicitly set ); PreparedStatement ps = session().prepare(selectQuery); ResultSet rows = session().execute(ps.bind().setInt(0, pk)); Row row = rows.one(); assertRow(row); }
@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); }
@Test(groups = "short") public void should_handle_contains_on_map_with_index() { PreparedStatement byFeatures = session() .prepare( select("id", "description", "features_values") .from("products") .where(contains("features_values", bindMarker("feature")))); ResultSet results = session().execute(byFeatures.bind().setString("feature", "LED")); Row row = results.one(); assertThat(row).isNotNull(); assertThat(row.getInt("id")).isEqualTo(29412); assertThat(row.getMap("features_values", String.class, String.class)) .containsEntry("techno", "LED"); }
/** * Tests that a value that was previously set on a bound statement can be unset by name. This only * works from protocol V4 onwards. * * @test_category prepared_statements:binding * @jira_ticket JAVA-930 * @since 2.2.0 */ @Test(groups = "short") @CassandraVersion("2.2.0") public void should_unset_value_by_name() { PreparedStatement prepared = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (:k, :i)"); BoundStatement bound = prepared.bind(); bound.setString("k", "foo"); bound.setInt("i", 1234); bound.unset("i"); assertThat(bound.isSet("i")).isFalse(); session().execute(bound); ResultSet rows = session() .execute( new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'") .enableTracing()); assertThat(rows.one().isNull("i")); // sleep 10 seconds to make sure the trace will be complete Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); QueryTrace queryTrace = rows.getExecutionInfo().getQueryTrace(); assertEventsContain(queryTrace, "0 tombstone"); }
/** * Validates that {@link PagingState} can be reused with the same {@link BoundStatement}. * * @test_category paging * @expected_result {@link ResultSet} from the query with the provided paging state starts from * the subsequent row from the first query. */ @Test(groups = "short") @CassandraVersion("2.0.0") public void should_be_able_to_use_state_with_bound_statement() { PreparedStatement prepared = session().prepare("SELECT v from test where k=?"); BoundStatement bs = prepared.bind(KEY); ResultSet result = session().execute(bs.setFetchSize(20)); int pageSize = result.getAvailableWithoutFetching(); PagingState pagingState = result.getExecutionInfo().getPagingState(); result = session().execute(bs.setFetchSize(20).setPagingState(pagingState)); // We have the result starting from the next page we stopped assertThat(result.one().getInt("v")).isEqualTo(pageSize); }
/** * Tests that a tombstone is created when binding a null value to a column in a prepared * statement. * * @test_category prepared_statements:binding * @jira_ticket JAVA-777 * @since 2.2.0 */ @Test(groups = "long") public void should_create_tombstone_when_null_value_on_bound_statement() { PreparedStatement prepared = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)"); BoundStatement st1 = prepared.bind(); st1.setString(0, "foo"); st1.setToNull(1); session().execute(st1); Statement st2 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'"); st2.enableTracing(); ResultSet rows = session().execute(st2); assertThat(rows.one().isNull(0)).isTrue(); // sleep 10 seconds to make sure the trace will be complete Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); QueryTrace queryTrace = rows.getExecutionInfo().getQueryTrace(); assertEventsContain(queryTrace, "1 tombstone"); }
@Test(groups = "short") public void should_use_collection_codecs_with_prepared_statements_2() { session() .execute( session() .prepare(insertQuery) .bind() .setInt(0, n_int) .setList(1, l_int) .setList(2, l_bigint, Long.class) // variant with element type explicitly set .setSet(3, s_float) .setSet( 4, s_double, TypeToken.of(Double.class)) // variant with element type explicitly set .setMap(5, m_varint) .setMap( 6, m_decimal, Integer.class, BigDecimal.class) // variant with element type explicitly set ); PreparedStatement ps = session().prepare(selectQuery); ResultSet rows = session().execute(ps.bind().setInt(0, n_int)); Row row = rows.one(); assertRow(row); }
@Test(groups = "short") public void should_truncate_blob_parameter_when_max_length_exceeded_bound_statements() throws Exception { // given normal.setLevel(TRACE); queryLogger = QueryLogger.builder().withMaxParameterValueLength(6).build(); cluster().register(queryLogger); // when String query = "UPDATE test SET c_blob = ? WHERE pk = ?"; PreparedStatement ps = session().prepare(query); BoundStatement bs = ps.bind(); bs.setBytes("c_blob", ByteBuffer.wrap(Bytes.toArray(Lists.newArrayList(1, 2, 3)))); bs.setInt("pk", 42); session().execute(bs); // then String line = normalAppender.waitAndGet(10000); assertThat(line) .contains("Query completed normally") .contains(ipOfNode(1)) .contains("c_blob:0x0102" + TRUNCATED_OUTPUT) .doesNotContain("0x010203"); }
@Test(groups = "short") public void should_allow_getting_and_setting_by_type_if_codec_registered() { String insertStmt = BoundStatement byName = insert.bind(); int byNameKey = keyCounter.incrementAndGet(); keys.add(byNameKey); byName.setInt("k", byNameKey); setValue(byName, "v", mapping.outerType, mapping.value); byName.setList("l", list, mapping.javaType); byName.setMap("m", map, mapping.javaType, mapping.javaType); if (is21) { byName.setTupleValue("t", tupleValue); byName.setSet("s", set, TypeTokens.listOf(mapping.javaType)); session().execute(byName); BoundStatement byIndex = insert.bind(); int byIndexKey = keyCounter.incrementAndGet(); keys.add(byIndexKey); byIndex.setInt(0, byIndexKey); setValue(byIndex, 1, mapping.outerType, mapping.value); byIndex.setList(2, list, mapping.javaType); byIndex.setMap(3, map, mapping.javaType, mapping.javaType); if (is21) { byIndex.setTupleValue(4, tupleValue); byIndex.setSet(5, set, TypeTokens.listOf(mapping.javaType));
@Test(groups = "short") public void prepareWithNullValuesTest() throws Exception { PreparedStatement ps = session().prepare("INSERT INTO " + SIMPLE_TABLE2 + "(k, v) VALUES (?, ?)"); session().execute(ps.bind("prepWithNull1", null)); BoundStatement bs = ps.bind(); bs.setString("k", "prepWithNull2"); bs.setString("v", null); session().execute(bs); ResultSet rs = session() .execute( "SELECT * FROM " + SIMPLE_TABLE2 + " WHERE k IN ('prepWithNull1', 'prepWithNull2')"); Row r1 = rs.one(); Row r2 = rs.one(); assertTrue(rs.isExhausted()); assertEquals(r1.getString("k"), "prepWithNull1"); assertEquals(r1.getString("v"), null); assertEquals(r2.getString("k"), "prepWithNull2"); assertEquals(r2.getString("v"), null); }
@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);
/** * Tests that a tombstone is NOT created when a column in a prepared statement is not bound (UNSET * flag). This only works from protocol V4 onwards. * * @test_category prepared_statements:binding * @jira_ticket JAVA-777 * @since 2.2.0 */ @Test(groups = "short") @CassandraVersion("2.2.0") public void should_not_create_tombstone_when_unbound_value_on_batch_statement_and_protocol_v4() { PreparedStatement prepared = session().prepare("INSERT INTO " + SIMPLE_TABLE + " (k, i) VALUES (?, ?)"); BoundStatement st1 = prepared.bind(); st1.setString(0, "foo"); st1.setInt(1, 1234); session().execute(new BatchStatement().add(st1)); BoundStatement st2 = prepared.bind(); st2.setString(0, "foo"); // i is UNSET session().execute(new BatchStatement().add(st2)); Statement st3 = new SimpleStatement("SELECT i from " + SIMPLE_TABLE + " where k = 'foo'"); st3.enableTracing(); ResultSet rows = session().execute(st3); assertThat(rows.one().getInt("i")).isEqualTo(1234); // sleep 10 seconds to make sure the trace will be complete Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); QueryTrace queryTrace = rows.getExecutionInfo().getQueryTrace(); assertEventsContain(queryTrace, "0 tombstone"); }
@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); }