Anorm and enum fields

1.3k Views Asked by At

I just wonder how can I use enum fileds (classes, extended from Enumeration) in my case classes with Anorm. For example:

object Type extends Enumeration {
    type Type = Value
    val User, Admin = Value
}

case class User (
    id: Pk[Long],
    type: Type.Type
)

If I try such code, I get "RuntimeException: no supported constructors for type models.User". What DB field type should I use for such purposes? I've tried varchar without luck.

1

There are 1 best solutions below

3
On

You can do it, with reflection. Given the code below(scala 2.10), do an import like

import AnormEnumerationExtension.ToId._

and your enum is persisted through it's id. And if you like to persist it's name use

import AnormEnumerationExtension.ToName._

Finally the EnumExtension:

import java.lang.reflect.InvocationTargetException
import scala.reflect.runtime.universe._

object AnormEnumerationExtension {      
  private lazy val rm = scala.reflect.runtime.currentMirror

  object ToId {
    implicit def enumToParameterValue[E <: Enumeration: TypeTag](enumValue: E#Value): ParameterValue[Int] = enumValue.id

    implicit def rowToEnumValue[E <: Enumeration: TypeTag]: Column[E#Value] = Column.nonNull { (value, meta) =>
      val MetaDataItem(qualified, _, _) = meta
      value match {
        case int: Int => {
          val methodSym = typeTag[E].tpe.member(newTermName("apply")).asMethod
          val im = rm.reflect(rm.reflectModule(typeOf[E].termSymbol.asModule).instance)
          try {
            Right(im.reflectMethod(methodSym)(int).asInstanceOf[E#Value])
          } catch {
            case e: InvocationTargetException if e.getCause.isInstanceOf[NoSuchElementException] =>
              Left(SqlMappingError(s"Can't convert $int to ${typeTag[E].tpe}, because it isn't a valid value: $qualified"))
          }
        }
        case _ => Left(TypeDoesNotMatch(s"Can't convert [$value:${value.asInstanceOf[AnyRef].getClass}] to ${typeTag[E].tpe}: $qualified"))
      }
    }
  }

  object ToName {
    implicit def enumToParameterValue[E <: Enumeration: TypeTag](enumValue: E#Value): ParameterValue[String] = enumValue.toString

    implicit def rowToEnumValue[E <: Enumeration: TypeTag]: Column[E#Value] = Column.nonNull { (value, meta) =>
      val MetaDataItem(qualified, _, _) = meta
      value match {
        case string: String => {
          val methodSym = typeTag[E].tpe.member(newTermName("withName")).asMethod
          val im = rm.reflect(rm.reflectModule(typeOf[E].termSymbol.asModule).instance)
          try {
            Right(im.reflectMethod(methodSym)(string).asInstanceOf[E#Value])
          }
          catch {
            case e: InvocationTargetException if e.getCause.isInstanceOf[NoSuchElementException] =>
              Left(SqlMappingError(s"Can't convert '$string' to ${typeTag[E].tpe}, because it isn't a valid value: $qualified"))
          }
        }
        case _ => Left(TypeDoesNotMatch(s"Can't convert [$value:${value.asInstanceOf[AnyRef].getClass}] to ${typeTag[E].tpe}: $qualified"))
      }
    }
  }
}