/** * Generates the necessary tables to store information. * * @throws Exception */ @Override public void createResource() throws Exception { cluster = builder.getCluster(); session = cluster.connect(); session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s with replication={'class':'SimpleStrategy', 'replication_factor':1};", keySpace)); session.execute(String.format("CREATE TABLE IF NOT EXISTS %s.%s (sink_id text, sub_id int, checkpoint_id bigint, PRIMARY KEY (sink_id, sub_id));", keySpace, table)); try { session.close(); } catch (Exception e) { LOG.error("Error while closing session.", e); } try { cluster.close(); } catch (Exception e) { LOG.error("Error while closing cluster.", e); } }
/** * Opens a Session to Cassandra and initializes the prepared statement. * * @param taskNumber The number of the parallel instance. * @throws IOException Thrown, if the output could not be opened due to an * I/O problem. */ @Override public void open(int taskNumber, int numTasks) throws IOException { this.session = cluster.connect(); this.prepared = session.prepare(insertQuery); this.callback = new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet ignored) { onWriteSuccess(ignored); } @Override public void onFailure(Throwable t) { onWriteFailure(t); } }; }
private void checkSizeEstimatesTableExist() { KeyspaceMetadata keyspaceMetadata = executeWithSession(session -> session.getCluster().getMetadata().getKeyspace(SYSTEM)); checkState(keyspaceMetadata != null, "system keyspace metadata must not be null"); TableMetadata table = keyspaceMetadata.getTable(SIZE_ESTIMATES); if (table == null) { throw new PrestoException(NOT_SUPPORTED, "Cassandra versions prior to 2.1.5 are not supported"); } }
/** Closes Cassandra driver session. */ public static void closeSession(Session driverSes) { if (driverSes == null) return; Cluster cluster = driverSes.getCluster(); if (!driverSes.isClosed()) U.closeQuiet(driverSes); if (!cluster.isClosed()) U.closeQuiet(cluster); }
@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(); }
@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); }
/** 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_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 should_set_routing_key_on_case_insensitive_keyspace_and_table() { session().execute(String.format("CREATE TABLE %s.foo (i int PRIMARY KEY)", keyspace)); PreparedStatement ps = session().prepare(String.format("INSERT INTO %s.foo (i) VALUES (?)", keyspace)); BoundStatement bs = ps.bind(1); assertThat(bs.getRoutingKey(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE)) .isNotNull(); }
@Test(groups = "short") public void should_set_registry_on_nested_udts() { ResultSet rows = session().execute("SELECT c1 FROM t1 WHERE pk = 1"); Row row = rows.one(); // here the CodecRegistry will create a codec on-the-fly using the UserType received from the // resultset metadata UDTValue udt1 = row.getUDTValue("c1"); assertThat(udt1.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry()); UDTValue udt2 = udt1.getUDTValue("f1"); assertThat(udt2.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry()); UDTValue udt3 = udt2.getUDTValue("f2"); assertThat(udt3.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry()); String f3 = udt3.getString("f3"); assertThat(f3).isEqualTo("foo"); }
@Test(groups = "short") public void should_set_registry_on_nested_tuples() { ResultSet rows = session().execute("SELECT c2 FROM t1 WHERE pk = 2"); Row row = rows.one(); // here the CodecRegistry will create a codec on-the-fly using the TupleType received from the // resultset metadata TupleValue tuple1 = row.getTupleValue("c2"); assertThat(tuple1.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry()); TupleValue tuple2 = tuple1.getTupleValue(0); assertThat(tuple2.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry()); TupleValue tuple3 = tuple2.getTupleValue(0); assertThat(tuple3.getCodecRegistry()).isSameAs(cluster().getConfiguration().getCodecRegistry()); String s = tuple3.getString(0); assertThat(s).isEqualTo("foo"); }
@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(); } }
@Test(groups = "short") public void should_execute_prepared_counter_statement() throws Exception { PreparedStatement p = session().prepare("UPDATE " + COUNTER_TABLE + " SET c = c + ? WHERE k = ?"); session().execute(p.bind(1L, "row")); session().execute(p.bind(1L, "row")); ResultSet rs = session().execute("SELECT * FROM " + COUNTER_TABLE); List<Row> rows = rs.all(); assertThat(rows).hasSize(1); assertThat(rows.get(0).getLong("c")).isEqualTo(2L); }
@Test(groups = "short") public void should_create_token_from_partition_key() { Metadata metadata = cluster().getMetadata(); Row row = session().execute("SELECT token(i) FROM foo WHERE i = 1").one(); Token expected = row.getToken(0); ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion(); assertThat(metadata.newToken(TypeCodec.cint().serialize(1, protocolVersion))) .isEqualTo(expected); }
@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_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 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"); } }
@SuppressWarnings("unchecked") private UDTValue convertValue(Object value, CassandraEntityMapper<?> mapper, CassandraClient cassandraClient) { String keyspace = cassandraClient.getSession().getLoggedKeyspace(); UserType userType = cassandraClient.getSession() .getCluster() .getMetadata() .getKeyspace(keyspace) .getUserType(mapper.getName()); UDTValue udtValue = userType.newValue(); for (String name : mapper.getNonKeyColumnNames()) { Object fieldValue = mapper.getColumnValueForName(name, value, cassandraClient); if (fieldValue != null) { udtValue.set(name, fieldValue, (Class<Object>) fieldValue.getClass()); } else { udtValue.setToNull(name); } } return udtValue; } }
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()));