Created
February 18, 2015 07:41
-
-
Save lazyvalue/09a72f1ac5461578a2ea to your computer and use it in GitHub Desktop.
Nasty little jdbc wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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