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

别说谁变了你拦得住时间么 提交于 2019-12-24 03:55:11

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/55100254/scala-slick-getting-a-typedtype-for-a-wrapped-optiont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!