Skip to content

Instantly share code, notes, and snippets.

@lazyvalue
Created February 18, 2015 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazyvalue/09a72f1ac5461578a2ea to your computer and use it in GitHub Desktop.
Save lazyvalue/09a72f1ac5461578a2ea to your computer and use it in GitHub Desktop.
Nasty little jdbc wrapper
import java.sql._
import scala.util.Try
object DbEnv {
trait Closeable {
def close: Unit
}
def arm[T <: Closeable,X](r: => T)(f: T => X) = {
val res = f(r)
r.close
res
}
type EnvF = () => Env
private val dateFormat = new java.text.SimpleDateFormat("MM/dd/YYYY")
implicit class ReadClob(clob: Clob) {
def read = clob.getSubString(1, clob.length.toInt)
}
class QueryRecord(rs: ResultSet) {
def mapOnFields(fields: Seq[String]): Map[String,String] =
Map[String,String](
(for {
name <- fields
value <- getAs[Object](name)
} yield name -> value.toString):_*)
def dateAsString(fieldName: String): String =
dateFormat.format(as(fieldName))
def as[T](fieldName: String) = rs.getObject(fieldName).asInstanceOf[T]
def getAs[T](fieldName: String) = Option(rs.getObject(fieldName)).flatMap(o => Try(o.asInstanceOf[T]).toOption)
def getClob(name: String): Option[String] = getAs[Clob](name).map(_.read)
def clob(name: String): String = as[Clob](name).read
}
class QueryResult(rs: ResultSet) {
def map[T](func: QueryRecord => T): Seq[T] = {
val lb = new scala.collection.mutable.ListBuffer[T]
val qr = new QueryRecord(rs)
while(rs.next) lb += func(qr)
rs.close
lb.toSeq
}
def foreach(func: QueryRecord => Unit) {
val qr = new QueryRecord(rs)
while(rs.next) func(qr)
rs.close
}
}
class Env(conn: Connection) extends Closeable {
def query(qstr: String): QueryResult = new QueryResult(conn.prepareStatement(qstr).executeQuery)
def idQuery(qStr: String, id: Int): QueryResult = {
val stmt = conn.prepareStatement(qStr)
stmt.setInt(1,id)
new QueryResult(stmt.executeQuery)
}
def close { conn.close }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment