made ResultSet.map() lazy by default - to save blowing RAM by always making a List of all results

This commit is contained in:
James Strachan
2012-08-02 12:41:52 +01:00
parent 9a33ca43bb
commit 7400a373b0
3 changed files with 3 additions and 23 deletions
@@ -33,7 +33,7 @@ fun ResultSet.iterator() : Iterator<ResultSet> {
/** /**
* Returns iterable that calls to the specified mapper function for each row * Returns iterable that calls to the specified mapper function for each row
*/ */
fun <T> ResultSet.getMapped(fn : (ResultSet) -> T) : jet.Iterable<T> { fun <T> ResultSet.map(fn : (ResultSet) -> T) : jet.Iterable<T> {
val rs = this val rs = this
val iterator = object : Iterator<T>{ val iterator = object : Iterator<T>{
@@ -90,26 +90,6 @@ fun ResultSet.get(columnId: Int): Any? = this.getObject(columnId)
*/ */
fun ResultSet.get(columnName: String): Any? = this.getObject(columnName) fun ResultSet.get(columnName: String): Any? = this.getObject(columnName)
/**
* Maps the collection of rows to some value
*/
fun <T> ResultSet.map(fn: (ResultSet) -> T) : List<T> {
val answer = ArrayList<T>()
mapTo(answer, fn)
return answer
}
/**
* Maps the collection of rows to some value and adds it to the result collection
*/
fun <T> ResultSet.mapTo(result: Collection<T>, fn: (ResultSet) -> T) : Collection<T> {
for (row in this) {
val element = fn(row)
result.add(element)
}
return result
}
private fun ResultSet.ensureHasRow() : ResultSet { private fun ResultSet.ensureHasRow() : ResultSet {
if (!next()) { if (!next()) {
throw IllegalStateException("There are no rows left in cursor") throw IllegalStateException("There are no rows left in cursor")
@@ -27,7 +27,7 @@ class JdbcTemplateTest {
val names = dataSource.query( val names = dataSource.query(
StringTemplate(array("select * from foo where id = ", id)) StringTemplate(array("select * from foo where id = ", id))
) { ) {
it.map{ it["name"] } it.map{ it["name"] }.toList()
} }
println("Found names $names") println("Found names $names")
@@ -62,7 +62,7 @@ class JdbcTest {
} }
dataSource.query("select * from foo") { dataSource.query("select * from foo") {
for (row in it.getMapped(mapper)) { for (row in it.map(mapper)) {
println(row) println(row)
} }
} }