M.Fooladgar M.Fooladgar - 3 months ago 32
Scala Question

Scala play withSession deprecated

I'm migrating from slick 2.1 to 3.0. As you know the function

withSession
has been deprecated.

How can I change code bellow:

def insert(vote: Vote) = DB.withSession { implicit session =>
insertWithSession(vote)
}
def insertWithSession(vote: Vote)(implicit s: Session) = {
Votes.insert(vote)
}


I've got compile error on
Votes.insert
and the error is:

could not find implicit value for parameter s: slick.driver.PostgresDriver.api.Session


At last, Is there any document other than official link helping me to migrate. I need more details.

Answer

Assuming that you are using play-slick for slick integration with play.

package yourproject.models

import play.api.db.slick.DatabaseConfigProvider
import slick.driver.JdbcProfile

case class Vote(subject: String, number: Int)

class VoteTable(tag: Tag) extends Table[Vote](tag, "votes") {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def subject = column[String]("subject")
  def number = column[Int]("number")

  def * = (id.?, subject, number) <> (Vote.tupled, Vote.unapply)
}

class VoteRepo @Inject()()(protected val dbConfigProvider: DatabaseConfigProvider) {
  val dbConfig = dbConfigProvider.get[JdbcProfile]
  val db = dbConfig.db
  import dbConfig.driver.api._

  val Votes = TableQuery[VoteTable]

  def insert(vote: Vote): DBIO[Long] = {
    Votes returning Votes.map(_.id) += vote
  }

}

Now your controller will look something like,

import javax.inject.Inject

import yourproject.models.{VoteRepo}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.{Action, Controller}

class Application @Inject()(voteRepo: VoteRepo) extends Controller {

  def createProject(subject: String, number: Int) = Action.async {
    implicit rs => {
      voteRepo.create(Vote(subject, number))
        .map(id => Ok(s"project $id created") )
    }
  }

}