Filtering when using custom column type in Slick

I'm having difficulty querying / filtering in Slick 2.1.0 when using a custom column type. A simplified version of my problem:

import scala.slick.driver.MySQLDriver.simple._ case class TableMapping(id: Long, status: Status) sealed trait Status { def intValue: Int } case object Active extends Status { override val intValue: Int = 1 } case object Disabled extends Status { override val intValue: Int = 2 } case object Deleted extends Status { override val intValue: Int = 3 } class MyTableDefinition(tag: Tag) extends Table[TableMapping](tag, "sometable") { implicit val statusColumnType = MappedColumnType.base[Status, Int](statusToInt, intToStatus) def id = column[Long]("ID", O.PrimaryKey, O.AutoInc) def status = column[Status]("STATUS", O.NotNull, O.Default(Active)) def * = (id, status) <> (TableMapping.tupled, TableMapping.unapply) private def statusToInt(s: Status): Int = s.intValue private def intToStatus(i: Int): Status = i match { case 1 => Active case 2 => Disabled case _ => Deleted } } class MyTableDao { val Items = TableQuery[MyTableDefinition] def byId(id: Long)(implicit session: Session): Option[TableMapping] = Items.filter(_.status =!= Deleted).firstOption } 

I get a compilation error:

 Items.filter(_.status =!= Deleted).firstOption 

Error:

value =! = is not a member of scala.slick.lifted.Column [Status] [error] def byId (id: Long) (implicit session: session): Option [TableMapping] = Items.filter (_. status =! = Deleted ) .firstOption

Any ideas on what I'm doing wrong? Maybe there is a much better way to do this that I don't know about?

+5
source share
2 answers

The thing is, the Scala compiler will look for an implicit conversion for Deleted.type instead of Status .

Since Deleted declared as an object , it is not a class, its actual class is Deleted.type , so you just need to help the compiler understand that it is actually a Status . How? You can try

 class MyTableDao { val Items = TableQuery[MyTableDefinition] def byId(id: Long)(implicit session: Session): Option[TableMapping] = Items.filter(_.status =!= Deleted.asInstanceOf[Status]).firstOption } 

It will be done.

Let me know if this worked, I ran into a similar problem and managed to get rid of it.

+6
source

Your custom transporter type must be in the DAO area; I would do something like:

 trait MyTypeMapper { protected implicit val statusColumnType = MappedColumnType.base[Status, Int](_.intValue, intToStatus) private def intToStatus(i: Int): Status = i match { case 1 => Active case 2 => Disabled case _ => Deleted } } 

and then mix the dash with your table mapper and tao:

 class MyTableDefinition(tag: Tag) extends Table[TableMapping](tag, "sometable") with MyTypeMapper {...} class MyTableDao extends MyTypeMapper{...} 
0
source

All Articles