/** * @param ses Session. * @param qry Query. * @param ctrl Control. * @param log Logger. * @param clo Closure for loaded values. */ public LoadCacheCustomQueryWorker(CassandraSession ses, String qry, PersistenceController ctrl, IgniteLogger log, IgniteBiInClosure<K, V> clo) { this(ses, new SimpleStatement(qry.trim().endsWith(";") ? qry : qry + ';'), ctrl, log, clo); }
private Set<String> getRandomUsers(PreparedStatement ps) { // lots of code. try { SimpleStatement query = new SimpleStatement(sql); query.setConsistencyLevel(ConsistencyLevel.QUORUM); // abstract the handling of the cache to it's own class. // this will need some work to make sure it's thread safe // as currently it's not. ResultSet res = session.execute(psCache.getStatement(sql));
protected int countBoundValues(BatchStatement bs) { int count = 0; for (Statement s : bs.getStatements()) { if (s instanceof BoundStatement) count += ((BoundStatement) s).wrapper.values.length; else if (s instanceof SimpleStatement) count += ((SimpleStatement) s).valuesCount(); } return count; }
/** * {@inheritDoc}. */ @Override public List<Statement> map(Map<String, Object> conf, Session session, ITuple tuple) { List<Column> columns = mapper.map(tuple); SimpleStatement statement = new SimpleStatement(queryString, Column.getVals(columns)); if (hasRoutingKeys()) { List<ByteBuffer> keys = rkGenerator.getRoutingKeys(tuple); if (keys.size() == 1) { statement.setRoutingKey(keys.get(0)); } else { statement.setRoutingKey(keys.toArray(new ByteBuffer[keys.size()])); } } return Arrays.asList((Statement) statement); }
@Test(groups = "short") public void should_pass_wrapped_statement_to_retry_policy() { retryPolicy.customStatementsHandled.set(0); // Set CL TWO with only one node, so the statement will always cause UNAVAILABLE, // which our custom policy ignores. Statement s = new SimpleStatement("select * from system.local").setConsistencyLevel(ConsistencyLevel.TWO); session().execute(s); assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(0); session().execute(new CustomStatement(s)); assertThat(retryPolicy.customStatementsHandled.get()).isEqualTo(1); }
@Test(groups = "unit") public void should_return_named_value() { Object expected = new Object(); Map<String, Object> namedValues = new HashMap<String, Object>(); namedValues.put("name", expected); Object actual = new SimpleStatement("doesn't matter", namedValues).getObject("name"); assertThat(actual).isEqualTo(expected); }
@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); }
/** * Validates that the "unsafe" paging state can be reused with the same Statement. * * @test_category paging * @expected_result {@link ResultSet} from the query with the provided raw paging state starts * from the subsequent row from the first query. */ @Test(groups = "short") public void should_complete_when_using_unsafe_paging_state() { SimpleStatement st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY)); ResultSet result = session().execute(st.setFetchSize(20)); int pageSize = result.getAvailableWithoutFetching(); byte[] savedPagingState = result.getExecutionInfo().getPagingStateUnsafe(); st = new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", KEY)); result = session().execute(st.setFetchSize(20).setPagingStateUnsafe(savedPagingState)); // We have the result starting from the next page we stopped assertThat(result.one().getInt("v")).isEqualTo(pageSize); }
@Test(groups = "short") public void should_use_CQL_timestamp_over_anything_else() { timestampFromGenerator = 10; String query = "INSERT INTO foo (k, v) VALUES (1, 1) USING TIMESTAMP 20"; session().execute(new SimpleStatement(query).setDefaultTimestamp(30)); long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0); assertEquals(writeTime, 20); }
@Test(groups = "unit") public void should_return_number_of_values() { assertThat(new SimpleStatement("doesn't matter").valuesCount()).isEqualTo(0); assertThat(new SimpleStatement("doesn't matter", 1, 2).valuesCount()).isEqualTo(2); } }
@Test(groups = "short") public void should_throw_ufe_when_protocol_version_lesser_than_4() throws Exception { try { Cluster v3cluster = register( Cluster.builder() .addContactPoints(getContactPoints()) .withPort(ccm().getBinaryPort()) .withProtocolVersion(V3) .build()) .init(); Session v3session = v3cluster.connect(); Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = ?", 1); statement.setOutgoingPayload(payload1); v3session.execute(statement); fail("Should not send custom payloads with protocol V3"); } catch (UnsupportedFeatureException e) { assertThat(e.getMessage()) .isEqualTo( "Unsupported feature with the native protocol V3 (which is currently in use): Custom payloads are only supported since native protocol V4"); } }
@Test( groups = "unit", expectedExceptions = {IllegalStateException.class}) public void should_throw_ISE_if_getObject_called_on_statement_without_values() { new SimpleStatement("doesn't matter").getObject(0); }
@Test(groups = "short") @CassandraVersion("2.1.0") public void should_execute_query_with_named_values() { // Given SimpleStatement statement = new SimpleStatement( "SELECT * FROM users WHERE id = :id and id2 = :id2", ImmutableMap.<String, Object>of("id", 1, "id2", 2)); // When Row row = session().execute(statement).one(); // Then assertThat(row).isNotNull(); assertThat(row.getString("name")).isEqualTo("test"); }
/** Ensures that a custom payload is propagated throughout pages. */ @Test(groups = "short") public void should_echo_custom_payload_when_paginating() throws Exception { session().execute("INSERT INTO t1 (c1, c2) VALUES (1, 'a')"); session().execute("INSERT INTO t1 (c1, c2) VALUES (1, 'b')"); Statement statement = new SimpleStatement("SELECT c2 FROM t1 where c1 = 1"); statement.setFetchSize(1); statement.setOutgoingPayload(payload1); ResultSet rows = session().execute(statement); rows.all(); assertThat(rows.getAllExecutionInfo()).extracting("incomingPayload").containsOnly(payload1); }
@Test(groups = "short") public void should_preserve_timestamp_when_retrying() { SimpleStatement statement = new SimpleStatement("INSERT INTO foo (k, v) VALUES (1, 1)"); statement.setDefaultTimestamp(10); // This will fail since we test against a single-host cluster. The // DowngradingConsistencyRetryPolicy // will retry it at ONE. statement.setConsistencyLevel(ConsistencyLevel.TWO); session().execute(statement); Errors metrics = session().getCluster().getMetrics().getErrorMetrics(); assertEquals(metrics.getRetriesOnUnavailable().getCount(), 1); long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0); assertEquals(writeTime, 10); } }
@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); } }
void compressionTest(ProtocolOptions.Compression compression) { cluster().getConfiguration().getProtocolOptions().setCompression(compression); try { Session compressedSession = cluster().connect(keyspace); compressedSession.execute( String.format( Locale.US, 42, 24.03f)); assertThat(rs.isExhausted()).isTrue(); checkExecuteResultSet(compressedSession.execute(SELECT_ALL), key); checkExecuteResultSet( compressedSession.execute( new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key); compressedSession .executeAsync( new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)) .getUninterruptibly(), key); .getConfiguration() .getProtocolOptions() .setCompression(ProtocolOptions.Compression.NONE);
@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 = "unit", expectedExceptions = {IllegalStateException.class}) public void should_throw_ISE_if_getValueNames_called_on_statement_without_named_values() { new SimpleStatement("doesn't matter").getValueNames(); }
@Test(groups = "short") public void simplePagingTest() { try { session().execute(String.format("INSERT INTO test (k, v) VALUES ('%s', %d)", key, i)); new SimpleStatement(String.format("SELECT v FROM test WHERE k='%s'", key)); st.setFetchSize(5); // Ridiculously small fetch size for testing purpose. Don't do at home. ResultSet rs = session().execute(st); assertFalse(rs.isFullyFetched()); assertFalse(rs.isExhausted()); assertEquals(rs.getAvailableWithoutFetching(), 5 - (i % 5)); assertEquals(rs.one().getInt(0), i); cluster().getConfiguration().getProtocolOptions().getProtocolVersion(), ProtocolVersion.V1);