Skip to content

Instantly share code, notes, and snippets.

@LeifWarner
Created June 5, 2012 19:13
Show Gist options
  • Save LeifWarner/2877089 to your computer and use it in GitHub Desktop.
Save LeifWarner/2877089 to your computer and use it in GitHub Desktop.
JDBC query using scala-arm
def sql[T](q: String)(f: ResultSet => T): Either[List[Throwable], T] = (for {
connection <- managed( datasource.getConnection )
statement <- managed( connection.createStatement )
resultSet <- managed( statement.executeQuery(q) )
} yield resultSet).acquireFor(f)
@jsuereth
Copy link

jsuereth commented Jul 7, 2012

def sql[T](q: String)(f: ResultSet => T): Either[List[Throwable], T] = 
  (for {
     connection <- managed(datasource.getConnection)
     statement <- managed(connection.createStatement)
     resultSet <- managed(statement executeQuery q)
   } yield resultSet) aquireFor f

Without so many ()....

And with delimited continuations:

def sql[T](q: String)(f: ResultSet => T): Either[List[Throwable],T] =
  withResources {
    def r[R: Resource](t: =>R) = managed(t).reflect[T]
    val connection = r(datasource.getConnection)
    val statement = r(connection.createStatement)
    val resultSet = r(statement executeQuery q)
    f(resultSet)
  }

The r function is a bit odd, but helps reduce some boilerplate. The code compiles to the same as before, it just looks "flat" if you prefer. The downside to delimited continuations is the failure to infer the type to the reflect call. That's why you have a bit more work here, but it's not bad.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment