如何在Scala中使用Typesafe

如何在Scala中使用Typesafe

本文介绍了如何在Scala中使用Typesafe Slick创建自定义列类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个enum的PostgreSQL表,该表由创建:

I have a PostgreSQL table with an enum, which is created by:

CREATE TYPE file_status AS ENUM ('new', 'uploading', 'queued', 'processing', 'done', 'failed');

和一个关联的字段

CREATE TABLE files ( ...
    status file_status NOT NULL,
    ...
);

使用Scala 2.10和Typesafe Slick 1.0.1,我创建了到我的Files表的映射,除了status字段(需要自定义file_status类型,字符串)外,它们的映射非常有用.

With Scala 2.10 and Typesafe Slick 1.0.1, I've created mappings to my Files table that work great with the exception of the status field, which requires the custom file_status type, a string.

def status = column[FileStatus]("status")

我一直在使用Slick的TypeMapper,但还不太清楚如何使它工作:

I've been playing with Slick's TypeMapper, but can't quite figure out how to get it to work:

sealed trait FileStatus

implicit val fileStatusMapper: TypeMapper[String] = base[FileStatus, String](
  s => s.toString,
  f => f(FileStatus)
)

我得到错误:类型不匹配;找到:models.Files.FileStatus.type必需:Int

为什么需要一个Int?是因为TypeMapper吗?我也尝试过

Why is an Int required? Is it because of the TypeMapper? I have also tried

...
f => f.toString
// type mismatch; found : String required: models.Files.FileStatus

f => f
// type mismatch; found : String required: models.Files.FileStatus

感谢您提供任何帮助我理解此映射的指示.

Thank you for any pointers in helping me understand this mapping.

推荐答案

从文档中引用():

// 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
)

使其适应文件状态:

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

更新:

另一个较少重复但也不太清晰的版本:

Another, less redundant, but possibly also less clear 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)
)

这篇关于如何在Scala中使用Typesafe Slick创建自定义列类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:35