Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Mapped Column Types In Slick Table Definition

Tags:

scala

slick

I have an enumerated type, ResourceType, that I'm trying to store in the database as an Int using the slick API. I have defined a custom type mapper for ResourceType, but I get a compiler error on my definition of * in my table definition saying that "No matching Shape found. Slick does not know how to map the given types.". Is it possible to make this work?

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

case class Resource(val id : Option[Int], val creationDate : Date, val title : String, val resourceType : ResourceType, val description : String) {
}

case class ResourceType private(val databaseCode : Int, val label : String) {
}

object ResourceType {
  val lessonPlan = new ResourceType(1, "Lesson Plan")
  val activity = new ResourceType(2, "Activity")

  val all = scala.collection.immutable.Seq(lessonPlan, activity)

  private val _databaseCodeMap = all.map(t => t.databaseCode -> t).toMap

  def apply(databaseCode : Int) = _databaseCodeMap(databaseCode)
}

class ResourceTable(tag : Tag) extends Table[Resource](tag, "Resource") {
  def id = column[Option[Int]]("ID", O.PrimaryKey, O.AutoInc)
  def creationDate = column[Date]("CreationDate")
  def title = column[String]("Title")
  def resourceType = column[Int]("ResourceType")
  def description = column[String]("Description")

  implicit val resourceTypeTypeMapper = MappedColumnType.base[ResourceType, Int](_.databaseCode, ResourceType(_))

  //Compile error on this line
  def * = (id, creationDate, title, resourceType, description) <> (Resource.tupled, Resource.unapply)
}
like image 974
Nimrand Avatar asked Jan 12 '23 10:01

Nimrand


1 Answers

The resourceType column needs to have the type ResourceType. So try

def resourceType = column[ResourceType]("ResourceType")

You may have to move the type mapper implicit above the column definition.

like image 153
Martin Kolinek Avatar answered Jan 17 '23 16:01

Martin Kolinek