How can I create a custom column type with Typesafe Slick in Scala?
Quoting from the docs (http://slick.typesafe.com/doc/1.0.1/lifted-embedding.html#user-defined-functions-and-types):
// An algebraic data type for booleanssealed trait Boolcase object True extends Boolcase object False extends Bool// And a TypeMapper that maps it to Int values 1 and 0implicit 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)
Adapting this to file status:
sealed trait FileStatuscase object New extends FileStatuscase object Uploading extends FileStatus...implicit val fileStatusTypeMapper = MappedTypeMapper.base[FileStatus, String]( { case New => "new" case Uploading => "uploading" ... },{ case "new" => New case "uploading" => Uploading ... })
Update:
Another, less redundant, but possibly also less clear version:
sealed trait FileStatuscase object New extends FileStatuscase object Uploading extends FileStatus...val statusMap = Map( New -> "new", Uploading -> "uploading", ...)implicit val fileStatusTypeMapper = MappedTypeMapper.base[FileStatus, String]( statusMap, statusMap.map(_.swap))
Slick 3.x version:
sealed trait FileStatus case object New extends FileStatus case object Uploading extends FileStatus ... implicit val fileStatusColumnType = MappedColumnType.base[FileStatus, String]( { case New => "new" case Uploading => "uploading" ... },{ case "new" => New case "uploading" => Uploading ... } )