Search code examples
scalaslicktype-safetyslick-3.0

Scala - Slick - Getting a TypedType for a wrapped Option[T]


It is usual to create custom IDs like this:

case class CustomID(value: Int) extends MappedTo[Int]

and to represent nullable custom IDs with types like Option[CustomID]. However, I would like to be able to move Option[_] into the case class, like this:

case class OptCustomID(optValue: Option[Int])

To be more specific, I am looking for a TypedType[OptCustomId] that behaves like the built-in TypedType[Option[Int]] for what concerns the database DDL.

Any ideas?


Solution

  • Actually you don't need TypedType[OptCustomId]. Correct way to handle table with field of type OptCustomID is described at the page http://slick.lightbend.com/doc/3.3.0/userdefined.html

      import slick.jdbc.PostgresProfile.api._
    
      case class OptCustomID(optValue: Option[Int])
      case class LiftedOptCustomID(optValue: Rep[Option[Int]])
      implicit object OptCustomIDShape extends CaseClassShape(LiftedOptCustomID, OptCustomID)
    
      case class Thing(id: OptCustomID, data: String)
      case class LiftedThing(id: LiftedOptCustomID, data: Rep[String])
      implicit object ThingShape extends CaseClassShape(LiftedThing.tupled, Thing.tupled)
    
      class ThingTable(tag: Tag) extends Table[Thing](tag, "things") {
        def id = column[Option[Int]]("id", O.PrimaryKey)
        def data = column[String]("data")
        def * = LiftedThing(LiftedOptCustomID(id), data)
      }
    
      val things = TableQuery[ThingTable]
      val result: DBIO[Option[Thing]] = things.filter(x => x.id === 1).result.headOption