Blocking API for Slick3
Slick is a powerful database access library for Scala. It provides flexible and type-safe query builder and asynchronous execution based on monadic API named DBIOAction. I’m Slick user since when it’s called as ScalaQeury. I’m loving it strongly.
DBIO was introduced in Slick3. It provided an elegant solution to run actions which access to the database asynchronous and parallel. However, it was difficult for non-functional programmers, and asynchronous or parallelism bring complexity essentially.
I had one question: “Is this complexity necessary for all applications?”
Slick2 has the blocking API and synchronous execution model. However it has not been maintained any more. Query compiler which generates SQL from Slick’s query AST is improving in Slick3, but they are not back ported to Slick2. Therefore we can’t choose Slick2 at the moment.
At last, I wrote a simple library to add the blocking API to Slick3:
This library adds some methods to execute query immediately to Slick3's Query object like this:
val db = Database.forURL("jdbc:h2:mem:test")
db.withSession { implicit session =>
// Create tables
models.Tables.schema.create
// Insert
Users.insert(UsersRow(1, "takezoe"))
// Select
val users: Seq[UserRow] = Users.list
// Select single record
val user: UserRow = Users.filter(_.id === "takezoe".bind).first
// Select single record with Option
val user: Option[UserRow] = Users.filter(_.id === "takezoe".bind).firstOption
// Update
Users.filter(t => t.id === 1.bind).update(UsersRow(1, "naoki"))
// Delete
Users.filter(t => t.id === 1.bind).delete
// Drop tables
models.Tables.schema.remove
}We can get both of Slick3's powerful and type-safe query builder and Slick2's simple execution model and the blocking API by this library.
Also here is an example of this library with Play2 and play-slick. If you are feeling difficulty or complexity in Slick3's monadic DBIO API, check this library. It might help you.
In addition, I found an issue about bringing back Slick2's blocking API in Slick project:
by porting it to master. No plans to implement this by the core maintainers, but we'd be supportive of a community…github.com
My hope is that the blocking API will be provided as a part of Slick project.