com.github.mperry.fg.SqlExtension.groovy Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of functionalgroovy-main Show documentation
Show all versions of functionalgroovy-main Show documentation
FunctionalGroovy enhances FunctionalJava for Groovy
package com.github.mperry.fg
import fj.F
import fj.Function
import fj.data.Stream
import groovy.sql.GroovyRowResult
import groovy.sql.Sql
import groovy.transform.TypeChecked
import groovy.transform.TypeCheckingMode
import java.sql.ResultSet
import java.sql.SQLException
/**
* Created by MarkPerry on 2/02/14.
*/
@TypeChecked
class SqlExtension {
@TypeChecked(TypeCheckingMode.SKIP)
static Stream streamRowResult(ResultSet rs, F f) {
stream(rs).map { ResultSet it ->
it.toRowResult()
}.map(f)
}
@TypeChecked(TypeCheckingMode.SKIP)
static Stream streamResultSet(ResultSet rs, F f) {
stream(rs).map(f)
}
static rx.Observable observableRowResult(ResultSet rs, F f) {
rx.Observable.from(streamRowResult(rs, f))
}
static rx.Observable observableResultSet(ResultSet rs, F f) {
rx.Observable.from(streamResultSet(rs, f))
}
static rx.Observable observableRowResultI(ResultSet rs, F f) {
rx.Observable.from(Stream.stream(1, 2, 3))
}
static B fold(Sql sql, String query, F, B> g) {
fold(sql, query, Function.identity(), g)
}
static B fold(Sql sql, String query, Closure f) {
fold(sql, query, f as F)
}
static B fold(Sql sql, String query, F f, F, B> g) {
def c
def s
try {
c = sql.getConnection()
s = c.createStatement()
def rs = s.executeQuery(query)
def b = g.f(streamResultSet(rs, f))
b
} catch (SQLException e) {
e.printStackTrace()
} finally {
// external function's responsibility to close the Sql resource
// sql.close()
}
}
@TypeChecked(TypeCheckingMode.SKIP)
static F rowResult() {
return { ResultSet rs -> rs.toRowResult() } as F
}
static B foldRowResult(Sql sql, String query, F, B> g) {
foldRowResult(sql, query, Function.identity(), g)
}
static B foldRowResult(Sql sql, String query, Closure f) {
foldRowResult(sql, query, f as F)
}
@TypeChecked(TypeCheckingMode.SKIP)
static B foldRowResult(Sql sql, String query, F f, F, B> g) {
fold(sql, query, Functions.o(f, rowResult()), g)
}
static Stream stream(ResultSet rs) {
SqlExtensionJava.toStream(rs)
}
static Stream stream(Sql sql, String query) {
try {
def c = sql.getConnection()
def s = c.createStatement()
def rs = s.executeQuery(query)
stream(rs)
} catch (SQLException e) {
throw e
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy