Slick 3 在自定义 SourceCodeGenerator 中使用自定义 MappedColumnType

Slick 3 use custom MappedColumnType in custom SourceCodeGenerator

我有这个使用默认 PostgresProfile 的自定义源代码生成器,我希望它在处理 java.sql.Timestamp 类型时生成 java.time.OffsetDateTime 列。我已经使用了 rawType,但我不明白我应该覆盖什么才能使用导入的隐式映射器。

当我 运行 codegen 任务时,它导入 SlickColumnMappers 但仅此而已。生成的列继续为 java.sql.Timestamp.

这对我来说是一个主要障碍。非常感谢帮助。

映射器

object SlickColumnMappers {
  implicit val TimestampToOffsetDateTime = MappedColumnType.base[OffsetDateTime, Timestamp](
    dt => Timestamp.from(dt.withOffsetSameInstant(ZoneOffset.UTC).toInstant),
    ts => OffsetDateTime.ofInstant(ts.toInstant, ZoneOffset.UTC)
  )
}

源代码生成器

new SourceCodeGenerator(model) {
  override def Table = new Table(_) {
    override def code: Seq[String] = Seq(
      "import helpers.SlickColumnMappers._"
    ) ++ super.code

    override def Column = new Column(_) {
      override def defaultCode = v => {
        def raw(v: Any) = rawType match {
          case "String" => "\"" + v + "\""
          case "Long" => v + "L"
          case "Float" => v + "F"
          case "Char" => "'" + v + "'"
          case "scala.math.BigDecimal" => s"scala.math.BigDecimal($v)"
          case "Byte" | "Short" | "Int" | "Double" | "Boolean" => v.toString
        }
        v match {
          case Some(x) => s"Some(${raw(x)})"
          case None => "None"
          case x => raw(x)
        }
      }
    }
  }
}

列映射允许您在 Row 模型中使用自定义 类,但不会影响代码生成。为了更改代码生成,您需要覆盖 SourceCodeGenerator

中的 Table 方法
  override def Table = new Table(_) {


    override def Column = new Column(_){
      override def rawType = {
        val superRawType = super.rawType
        superRawType match {
          case "java.sql.Timestamp" => "java.time.ZonedDateTime"
          case "java.sql.Date" => "java.time.LocalDate"
          case x => x
        }
      }
}