How to combine multiple columns in one case class field when using lifted embedding?

允我心安 提交于 2019-12-04 17:56:34

You can provide your own constructor and extractor functions for User objects to Slick using the <> function on the * projection. Something like this:

class User extends Table[User](...){
  ...
  def * = col1 ~ col2 ~ col3 ~ col4 <> (constructUser, extractUser)
}

def constructUser( col1: T1, col2: T2, col3: T3, col4: T4 )
  = User(col1, Roles(col2, col3, col4))
def extractUser( user: User ) = user match{
  case User(col1, Roles(col2, col3, col4)) =>  (col1, col2, col3, col4)
}

object Roles{
  def apply( col2: T2, col3: T3, col4: T4 ) : Set[Role]  = ...
  def unapply( roles: Set[Role] ) : Option[(T2, T3, T4)] = ...
}

Also see http://slick.typesafe.com/doc/1.0.1/lifted-embedding.html#mapped-tables

This is possible, you can use an Enumeration or roles:

object Role extends Enumeration with BitmaskedEnumeration {
  type Role = Value
  val Editor, Moderator, Administrator, Usermoderator, Usermoderator2,
      Partner, PremiumPartner, CorporatePaid = Value
}
import Role._

A field of type Role can then be used in your Slick Table "as is", like any of the native types.
Here is the code for BitmaskedEnumeration:

import slick.jdbc.GetResult
import slick.lifted.{BaseTypeMapper, MappedTypeMapper}

/** Source: https://github.com/nafg/slick-additions. */
trait Bitmasked {
  type Value
  def bitFor: Value => Int
  def forBit: Int => Value
  def values: Iterable[Value]
  def longToSet: Long => Set[Value] =
    bm => values.toSeq.filter(v => 0 != (bm & (1 << bitFor(v)))).toSet
  def setToLong: Set[Value] => Long =
    _.foldLeft(0L){ (bm, v) => bm + (1L << bitFor(v)) }

  implicit lazy val enumTypeMapper: BaseTypeMapper[Value] =
    MappedTypeMapper.base[Value, Int](bitFor, forBit)
  implicit lazy val enumSetTypeMapper: BaseTypeMapper[Set[Value]] =
    MappedTypeMapper.base[Set[Value], Long](setToLong, longToSet)

  implicit lazy val getResult: GetResult[Value] =
    GetResult(r => forBit(r.nextInt))
  implicit lazy val getSetResult: GetResult[Set[Value]] =
    GetResult(r => longToSet(r.nextLong))
}

/** Mix this class into a subclass of Enumeration to have it usable as a
  * column type in a Slick Table. */
trait BitmaskedEnumeration extends Bitmasked { this: Enumeration =>
  def bitFor = _.id
  def forBit = apply(_)
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!