使用提升嵌入时如何在一个案例类字段中组合多个列?

时间:2013-09-02 11:24:26

标签: scala slick

我们有一个MySQL表,其中包含几个布尔列,用于指定用户可能拥有的角色。是否有可能通过光滑的提升嵌入来编写一个类型映射器,它结合了&将这些多列转换为案例类User中的一个字段,如下所示?

case class User(id: Option[Int], nickname: String, role: Seq[Role.Role])

object Users extends Table[(User)]("ask_user") {
      def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
      def nickname = column[String]("nickname")
      def is_editor = column[Boolean]("is_editor")
      def is_moderator = column[Boolean]("is_moderator")
      def is_administrator = column[Boolean]("is_administrator")
      def is_usermoderator = column[Boolean]("is_usermoderator")
      def is_usermoderator2 = column[Boolean]("is_usermoderator2")
      def is_partner = column[Boolean]("is_partner")
      def is_premium_partner = column[Boolean]("is_premium_partner")
      def is_corporate_paid = column[Boolean]("is_corporate_paid") 
    }

2 个答案:

答案 0 :(得分:5)

您可以使用<>为用户对象提供自己的构造函数和提取函数。 *投影上的功能。像这样:

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)] = ...
}

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

答案 1 :(得分:-1)

这是可能的,您可以使用枚举或角色:

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

然后,类似Role的字段可以在“Slick Table”中“按原样”使用,就像任何本机类型一样。
以下是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(_)
}