13.09.2013

Slick in Scala: Combining multiple fields in one mapping case class field

Yesterday I've had a problem with an existing database schema. In one table there were several Boolean columns each expressing the existence of an user role.

Since we use Slick for MySQL access in our services, I wanted to combine these several columns in one single (enumeration) field of the mapping case class:
This can be achieved by providing your own constructor and extractor functions for User objects to Slick using the <> function on the * projection. Something like this:
Be sure that your own constructor and extractor functions have the apply/unapply style, e.g. extractUser should return an Option of a tuple, if it does not (extractUser returns a tuple instead of an option of a tuple) you get a hard-to-read error message from the compiler:
overloaded method value <> with alternatives:
  [R(in method <>)...
    userModeratorMajor ~ partner ~ premiumPartner ~ corporatePaid <> (constructUser _, extractUser _)
Thanks Mr. Vogt from Typesafe for the hint.