0

This is basically the repeat of an earlier question, but with respect to Slick-2, as the answers that worked for v.1 don't work anymore.

In short, Slick documentation suggests to do something like this

package models
import scala.slick.driver.H2Driver.simple._

class Pictures(tag: Tag) extends Table[(Int, String, String)](tag, "Pictures") {
    def id = column[Int]("id", O.PrimaryKey)
    def urlThumb = column[String]("urlThumb", O.NotNull)
    def urlLarge = column[String]("urlLarge", O.NotNull)
    def * = (id, urlThumb, urlLarge)
}

This is tying the code directly to H2Driver. I want it to be driver-agnostic, i.e. to work with any JdbcProfile driver. The only way I found to do it is by passing the driver to the DAO class

class SlickDAO(val driver: JdbcProfile) {
    import driver.simple._

The problem with that is if I want to define some traits with shared behavior, e.g. CRUDSupport, I can't have arguments to the trait, I can only do an abstract class. So I am curious what is the recommended way of writing the DAL with Slick-2? I'm sure it's the Cake pattern, but I am not advanced enough in Scala to implement it.

Community
  • 1
  • 1
Yuri Shkuro
  • 564
  • 1
  • 3
  • 15

2 Answers2

1

I don't know specifically about Slick, but there are standard Scala approaches to this problem.

I can't have arguments to the trait, I can only do an abstract class

But you can have

trait SlickDAO {
  val driver: JdbcProfile

  import driver.simple._
  ...
}

and later

class SlickDAOImpl(val driver: JdbcProfile) extends SlickDAO

or

 new SlickDAO {
   val driver = ...
 }

However, using abstract vals in traits can lead to problems with initialization order, so I'd prefer

trait SlickDAO {
  // can still be implemented as a val
  def driver: JdbcProfile

  // can't import driver.simple._, you'll have to write the prefix explicitly
  ...
}

or

trait SlickDAO {
  def getDriver: JdbcProfile
  lazy val driver = getDriver

  import driver.simple._
  ...
}
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
0

Take a look at: http://knoldus.wordpress.com/?p=5228&preview=true and :https://github.com/satendrakumar06/slickformultipledatabases it might be helpful.

Sky
  • 2,509
  • 1
  • 19
  • 28