Skip to content

Commit

Permalink
Add stream() method for convenient result traversal (#24525)
Browse files Browse the repository at this point in the history
---------

Co-authored-by: Krzysztof Jamróz <79092062+k-jamroz@users.noreply.github.com>
  • Loading branch information
TomaszGaweda and k-jamroz committed Jul 4, 2023
1 parent e7514d2 commit 69d15f6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.util.List;

import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

Expand Down Expand Up @@ -79,13 +80,9 @@ private void check(boolean client) {
}

private List<SqlRow> execute(String query) {
List<SqlRow> rows = new ArrayList<>();
try (SqlResult result = instance().getSql().execute(query)) {
for (SqlRow row : result) {
rows.add(row);
}
return result.stream().collect(toList());
}
return rows;
}

private void checkSuccess(
Expand Down
23 changes: 23 additions & 0 deletions hazelcast/src/main/java/com/hazelcast/sql/SqlResult.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

import javax.annotation.Nonnull;
import java.util.Iterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
* SQL query result. Depending on the statement type it represents a stream of
Expand Down Expand Up @@ -82,6 +84,27 @@ default boolean isRowSet() {
@Override
Iterator<SqlRow> iterator();

/**
* Returns a stream of result rows.
* <p>It uses internally {@link #iterator()} method, so it cannot be called twice.</p>
*
* <p>You should still call {@link #close()} method after the stream is used (or use this method inside
* {@code try-with-resources} block. You should not pass the {@link Stream} from this method outside
* {@code try-with-resources} block, if it's used.</p>
*
* @throws IllegalStateException if the method is invoked more than once or
* if this result doesn't have rows
* @throws HazelcastSqlException in case of an SQL-related error condition
*
* @return Stream of result rows
*
* @since 5.4
*/
@Nonnull
default Stream<SqlRow> stream() {
return StreamSupport.stream(spliterator(), false);
}

/**
* Returns the number of rows updated by the statement or -1 if this result
* is a row set. In case the result doesn't contain rows but the update
Expand Down

0 comments on commit 69d15f6

Please sign in to comment.