PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

Wie kann ich mit Typesafe Slick in Scala einen benutzerdefinierten Spaltentyp erstellen?

Zitieren aus den Dokumenten ( http://slick.typesafe.com/doc/1.0.1/lifted-embedding.html#user-defined-functions-and-types ):

// An algebraic data type for booleans
sealed trait Bool
case object True extends Bool
case object False extends Bool

// And a TypeMapper that maps it to Int values 1 and 0
implicit val boolTypeMapper = MappedTypeMapper.base[Bool, Int](
  { b => if(b == True) 1 else 0 },    // map Bool to Int
  { i => if(i == 1) True else False } // map Int to Bool
)

Anpassung an Dateistatus:

sealed trait FileStatus
case object New extends FileStatus
case object Uploading extends FileStatus
...

implicit val fileStatusTypeMapper = MappedTypeMapper.base[FileStatus, String](
  {
    case New => "new"
    case Uploading => "uploading"
    ...
  },{
    case "new" => New
    case "uploading" => Uploading
    ...
  }
)

Aktualisierung:

Eine andere, weniger redundante, aber möglicherweise auch weniger klare Version:

sealed trait FileStatus
case object New extends FileStatus
case object Uploading extends FileStatus
...

val statusMap = Map(
    New -> "new",
    Uploading -> "uploading",
    ...
)

implicit val fileStatusTypeMapper = MappedTypeMapper.base[FileStatus, String](
  statusMap,
  statusMap.map(_.swap)
)