Last active
August 1, 2016 10:59
-
-
Save takezoe/28f7a462666d8969fd7433798774fc2f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 slick.ast.{CompiledStatement, ResultSetMapping} | |
import slick.driver.{H2Driver, JdbcProfile} | |
import slick.jdbc.{JdbcBackend, JdbcResultConverterDomain} | |
import slick.lifted.Query | |
import slick.relational.{CompiledMapping, ResultConverter} | |
import slick.util.SQLBuilder | |
/** | |
* To use the blocking APIs, import BlockingH2Driver as follows: | |
* | |
* import BlockingH2Driver._ | |
* import BlockingH2Driver.api._ | |
*/ | |
object BlockingH2Driver extends H2Driver with SlickBlockingAPI | |
trait SlickBlockingAPI { self: JdbcProfile => | |
implicit class Slick2LikeQueryInvoker[U, C[_]](q: Query[_ ,U, C]){ | |
def list(implicit session: JdbcBackend#Session): Seq[U] = { | |
val invoker = createQueryInvoker[U](queryCompiler.run(q.toNode).tree, null, null) | |
invoker.results(0).right.get.toSeq | |
} | |
def first(implicit session: JdbcBackend#Session): U = { | |
val invoker = createQueryInvoker[U](queryCompiler.run(q.toNode).tree, null, null) | |
invoker.first | |
} | |
def firstOption(implicit session: JdbcBackend#Session): Option[U] = { | |
val invoker = createQueryInvoker[U](queryCompiler.run(q.toNode).tree, null, null) | |
invoker.firstOption | |
} | |
def unsafeDelete(implicit session: JdbcBackend#Session): Int = { | |
val tree = deleteCompiler.run(q.toNode).tree | |
val ResultSetMapping(_, CompiledStatement(_, sres: SQLBuilder.Result, _), _) = tree | |
session.withPreparedStatement(sres.sql){ st => | |
sres.setter(st, 1, null) | |
st.executeUpdate | |
} | |
} | |
def unsafeUpdate[T](value: T)(implicit session: JdbcBackend#Session): Int = { | |
val tree = updateCompiler.run(q.toNode).tree | |
val ResultSetMapping(_, CompiledStatement(_, sres: SQLBuilder.Result, _), CompiledMapping(_converter, _)) = tree | |
val converter = _converter.asInstanceOf[ResultConverter[JdbcResultConverterDomain, T]] | |
session.withPreparedInsertStatement(sres.sql) { st => | |
st.clearParameters | |
converter.set(value, st) | |
sres.setter(st, converter.width+1, null) | |
st.executeUpdate | |
} | |
} | |
def unsafeInsert[U](value: U)(implicit session: JdbcBackend#Session): Int = { | |
val compiled = compileInsert(q.toNode) | |
val a = compiled.standardInsert | |
session.withPreparedStatement(a.sql) { st => | |
st.clearParameters() | |
a.converter.set(value, st) | |
st.executeUpdate() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment