/** * 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); } }
public Cluster getCluster() { return buildCluster(Cluster.builder()); }
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"); } }
/** * {@inheritDoc} */ @Override public void close() { if (cluster != null && !cluster.isClosed()) { LOG.info("Try to close connection to cluster: {}", cluster.getClusterName()); session.close(); cluster.close(); } }
@Inject public DataStaxClusterImpl(final CassandraConfig cassandraFig ) throws Exception { this.cassandraConfig = cassandraFig; this.cluster = getCluster(); logger.info("Initialized datastax cluster client. Hosts={}, Idle Timeout={}s, Pool Timeout={}s", getCluster().getMetadata().getAllHosts().toString(), getCluster().getConfiguration().getPoolingOptions().getIdleTimeoutSeconds(), getCluster().getConfiguration().getPoolingOptions().getPoolTimeoutMillis() / 1000); // always initialize the keyspaces this.createApplicationKeyspace(false); this.createApplicationLocalKeyspace(false); }
@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_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_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 = "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(); } }
@SuppressWarnings("deprecation") @Test(groups = "short") public void should_handle_collections_of_tuples() { String query; BuiltStatement statement; query = "UPDATE foo SET l=[(1,2)] WHERE k=1;"; TupleType tupleType = cluster().getMetadata().newTupleType(cint(), cint()); List<TupleValue> list = ImmutableList.of(tupleType.newValue(1, 2)); statement = update("foo").with(set("l", list)).where(eq("k", 1)); assertThat(statement.toString()).isEqualTo(query); } }
@Test(groups = "short") public void should_log_all_parameter_types_bound_statements() throws Exception { // given normal.setLevel(TRACE); queryLogger = QueryLogger.builder().withMaxParameterValueLength(Integer.MAX_VALUE).build(); cluster().register(queryLogger); // when String query = "UPDATE test SET " + assignments + " WHERE pk = 42"; PreparedStatement ps = session().prepare(query); BoundStatement bs = ps.bind(values.toArray()); session().execute(bs); // then String line = normalAppender.waitAndGet(10000); assertThat(line).contains("Query completed normally").contains(ipOfNode(1)).contains(query); CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry(); for (DataType type : dataTypes) { TypeCodec<Object> codec = codecRegistry.codecFor(type); assertThat(line).contains(codec.format(getFixedValue(type))); } }
@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(); } }
@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 should_countdown_inflight_requests_metrics() { sCluster .node(1) .primingClient() .prime(PrimingRequest.queryBuilder().withQuery("mock query").withThen(then()).build()); Cluster cluster = null; try { cluster = builder().build(); Session session = cluster.connect(); assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0); session.executeAsync("mock query").getUninterruptibly(); session.executeAsync("mock query").getUninterruptibly(); assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0); } finally { if (cluster != null) { cluster.close(); } } } }
@Test(groups = "short") @BMRule( name = "emulate OOME", targetClass = "com.datastax.driver.core.Connection$4", targetMethod = "apply(Void)", action = "throw new OutOfMemoryError(\"not really\")") public void should_propagate_errors() { try { cluster.connect(); fail("Expecting OOME"); } catch (OutOfMemoryError e) { assertThat(e).hasMessage("not really"); } }
@Test(groups = "short") public void should_connect_with_credentials() { PlainTextAuthProvider authProvider = spy(new PlainTextAuthProvider("cassandra", "cassandra")); Cluster cluster = Cluster.builder() .addContactPoints(getContactPoints()) .withPort(ccm().getBinaryPort()) .withAuthProvider(authProvider) .build(); cluster.connect(); verify(authProvider, atLeastOnce()) .newAuthenticator( findHost(cluster, 1).getSocketAddress(), "org.apache.cassandra.auth.PasswordAuthenticator"); assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount()) .isEqualTo(0); }
@Test(groups = "short") public void should_be_invoked_at_shutdown() { try { cluster().connect(); cluster().close(); } finally { assertThat(policy.wasClosed).isTrue(); } }
@Test(groups = "short") public void should_escape_single_quote_table_comment() { // given String cql = String.format( "CREATE TABLE %s.single_quote (\n" + " c1 int PRIMARY KEY\n" + ") WITH comment = 'comment with single quote '' should work'", keyspace); // when session().execute(cql); TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("single_quote"); // then assertThat(table.getOptions().getComment()) .isEqualTo("comment with single quote ' should work"); assertThat(table.asCQLQuery()).contains("comment = 'comment with single quote '' should work'"); }
@Test(groups = "short") public void remainingDeleteTests() throws Exception { Statement query; TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_TEXT); assertNotNull(table); String expected = String.format("DELETE k FROM %s.test_text;", keyspace); query = delete("k").from(table); assertEquals(query.toString(), expected); try { session().execute(query); fail(); } catch (SyntaxError e) { // Missing WHERE clause } }