soda-for-java icon indicating copy to clipboard operation
soda-for-java copied to clipboard

Support for-each loop and forEach() for OracleCursor

Open gvenzl opened this issue 6 years ago • 3 comments

OracleCursor should be enabled to to be used in the Java for-each loop as well as the Java 8 forEach() streams implementation. The .getCursor() operation will return a cursor to self-contained OracleDocument objects. Right now the user has to write ugly boiler plate code to iterate over these documents, e.g.:

OracleCursor c = col.find().getCursor();

while (c.hasNext()) {
  OracleDocument resultDoc = c.next();
  System.out.println("Document content: " + resultDoc.getContentAsString());
}

c.close;

This should be simplified to allow the user to use the for-each construct instead:

for (OracleDocument resultDoc : col.find().getCursor()) {
  System.out.println("Document content: " + resultDoc.getContentAsString());
}

gvenzl avatar May 28 '19 10:05 gvenzl

We've considered various ways to support "for each" with the Cursor, but it's not doable. The issue is having to implement Iterable/Iterator, those are not appropriate for the Cursor (for example, we want to throw custom SODA exceptions from next(), with SQLException attached as the cause, which we can't do with the Iterator next()).

We could potentially add getDocuments(), which will return all the documents fetched by the operation as some kind of an array, and you'd be able to use the "for each" loop on that. We'll look into it.

As far as Java 8 forEach, will investigate to see what we can do.

morgiyan avatar May 29 '19 01:05 morgiyan

You could always define an unchecked exception but then it isn't clear to me how the close() would be communicated (e.g. on error, early exit, etc). Lambdas may be a better fit. Something like

col.find().forEach( resultDoc -> {
    System.out.println("Document content: " + resultDoc.getConentAsString());
});

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#forEach-java.util.function.Consumer-

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

jjspiegel avatar May 29 '19 03:05 jjspiegel

We considered unchecked exceptions but didn't want to go that route.

For forEach, I'll look into it.

morgiyan avatar May 29 '19 03:05 morgiyan