/** * Retrieve the Cassandra release version. * * @param session must not be {@literal null}. * @return the release {@link Version}. */ public static Version getReleaseVersion(Session session) { Assert.notNull(session, "Session must not be null"); ResultSet resultSet = session.execute("SELECT release_version FROM system.local;"); Row row = resultSet.one(); return Version.parse(row.getString(0)); } }
@VisibleForTesting String lookupWorkflowIdFromTaskId(String taskId) { try { ResultSet resultSet = session.execute(selectTaskLookupStatement.bind(UUID.fromString(taskId))); return Optional.ofNullable(resultSet.one()) .map(row -> row.getUUID(WORKFLOW_ID_KEY).toString()) .orElse(null); } catch (Exception e) { Monitors.error(CLASS_NAME, "lookupWorkflowIdFromTaskId"); String errorMsg = String.format("Failed to lookup workflowId from taskId: %s", taskId); LOGGER.error(errorMsg, e); throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, errorMsg, e); } } }
private void removeTaskLookup(Task task) { try { recordCassandraDaoRequests("removeTaskLookup", task.getTaskType(), task.getWorkflowType()); session.execute(deleteTaskLookupStatement.bind(UUID.fromString(task.getTaskId()))); } catch (Exception e) { Monitors.error(CLASS_NAME, "removeTaskLookup"); String errorMsg = String.format("Failed to remove task lookup: %s", task.getTaskId()); LOGGER.error(errorMsg, e); throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, errorMsg); } }
scanStmt.append(QueryBuilder.bindMarker()); stmt = session.prepare(scanStmt.toString()); stmt.setConsistencyLevel(readConsistencyLevel); if (trace) { logger.debug("startKey = {}, recordcount = {}", startkey, recordcount); ResultSet rs = session.execute(stmt.bind(startkey, Integer.valueOf(recordcount))); Row row = rs.one(); tuple = new HashMap<String, ByteIterator>();
@Test(groups = "short") public void should_pass_wrapped_statement_to_load_balancing_policy() { loadBalancingPolicy.customStatementsHandled.set(0); SimpleStatement s = new SimpleStatement("select * from system.local"); session().execute(s); assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(0); session().execute(new CustomStatement(s)); assertThat(loadBalancingPolicy.customStatementsHandled.get()).isEqualTo(1); }
@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"); }
@Test(groups = "short") public void should_use_server_side_timestamp_if_none_specified() { timestampFromGenerator = Long.MIN_VALUE; long clientTime = System.currentTimeMillis() * 1000; String query = "INSERT INTO foo (k, v) VALUES (1, 1)"; session().execute(query); long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0); assertTrue(writeTime >= clientTime); }
private void should_iterate_result_set_asynchronously(int totalCount, int fetchSize) { for (int i = 0; i < totalCount; i++) session().execute(String.format("insert into ints (i) values (%d)", i)); Statement statement = new SimpleStatement("select * from ints").setFetchSize(fetchSize); ResultsAccumulator results = new ResultsAccumulator(); ListenableFuture<ResultSet> future = GuavaCompatibility.INSTANCE.transformAsync(session().executeAsync(statement), results); Futures.getUnchecked(future); assertThat(results.all.size()).isEqualTo(totalCount); }
@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_pass_wrapped_statement_to_speculative_execution_policy() { speculativeExecutionPolicy.customStatementsHandled.set(0); SimpleStatement s = new SimpleStatement("select * from system.local"); session().execute(s); assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(0); session().execute(new CustomStatement(s)); assertThat(speculativeExecutionPolicy.customStatementsHandled.get()).isEqualTo(1); }
@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); }
@Test(groups = "short") public void should_use_generator_timestamp_if_none_other_specified() { timestampFromGenerator = 10; String query = "INSERT INTO foo (k, v) VALUES (1, 1)"; session().execute(query); long writeTime = session().execute("SELECT writeTime(v) FROM foo WHERE k = 1").one().getLong(0); assertEquals(writeTime, 10); }
@Override public VersionNumber getCassandraVersion() { ResultSet result = executeWithSession(session -> session.execute("select release_version from system.local")); Row versionRow = result.one(); if (versionRow == null) { throw new PrestoException(CASSANDRA_VERSION_ERROR, "The cluster version is not available. " + "Please make sure that the Cassandra cluster is up and running, " + "and that the contact points are specified correctly."); } return VersionNumber.parse(versionRow.getString("release_version")); }
@Override public boolean removeWorkflow(String workflowId) { Workflow workflow = getWorkflow(workflowId, true); boolean removed = false; // TODO: calculate number of shards and iterate if (workflow != null) { try { recordCassandraDaoRequests("removeWorkflow", "n/a", workflow.getWorkflowName()); ResultSet resultSet = session.execute(deleteWorkflowStatement.bind(UUID.fromString(workflowId), DEFAULT_SHARD_ID)); if (resultSet.wasApplied()) { removed = true; } } catch (Exception e) { Monitors.error(CLASS_NAME, "removeWorkflow"); String errorMsg = String.format("Failed to remove workflow: %s", workflowId); LOGGER.error(errorMsg, e); throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, errorMsg); } workflow.getTasks().forEach(this::removeTaskLookup); } return removed; }
@VisibleForTesting WorkflowMetadata getWorkflowMetadata(String workflowId) { ResultSet resultSet = session.execute(selectTotalStatement.bind(UUID.fromString(workflowId))); recordCassandraDaoRequests("getWorkflowMetadata"); return Optional.ofNullable(resultSet.one()) .map(row -> { WorkflowMetadata workflowMetadata = new WorkflowMetadata(); workflowMetadata.setTotalTasks(row.getInt(TOTAL_TASKS_KEY)); workflowMetadata.setTotalPartitions(row.getInt(TOTAL_PARTITIONS_KEY)); return workflowMetadata; }).orElseThrow(() -> new ApplicationException(ApplicationException.Code.NOT_FOUND, String.format("Workflow with id: %s not found in data store", workflowId))); }
@Test(groups = "short", expectedExceptions = NoHostAvailableException.class) public void should_not_reprepare_invalid_statements() { // given session().execute("ALTER TABLE prepared_statement_invalidation_test ADD d int"); PreparedStatement ps = session() .prepare("SELECT a, b, c, d FROM prepared_statement_invalidation_test WHERE a = ?"); session().execute("ALTER TABLE prepared_statement_invalidation_test DROP d"); // when session().execute(ps.bind()); }
@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); }