在 Quill 中使用 Postgres 枚举

问题描述 投票:0回答:2

我正在尝试将 Scala 2 枚举与 Quill 一起使用,如下所示:

import io.getquill.MappedEncoding

object MyEnumType extends Enumeration {
  type MyEnumType = Value

  val ONE, TWO, THREE = Value

  implicit val encode: MappedEncoding[MyEnumType, String] =
    MappedEncoding(_.toString)
  implicit val decode: MappedEncoding[String, MyEnumType] =
    MappedEncoding(MyEnumType.withName)
}

但我最终遇到了 Postgres 的错误:

ERROR: operator does not exist: my_enum_type = character varying
  Hint: No operator matches the given name and argument types. You might need to add explicit type casts.

我正在使用

translate
打印出查询,查询是这样生成的:

WHERE column_1 = ONE

我在哪里期待它被渲染成:

WHERE column_1 = 'ONE'

在 Scala 2.13 中使用 Quill 处理枚举的正确方法是什么?

编辑

我一直在试验,包括使用 Enumeratum 库,但仍然没有正确生成枚举值。

使用调试器,我可以看到正在评估自定义编码器,但结果值从未进入生成的查询。

我在这里发布了一个问题示例:
https://gist.github.com/daharon/97e8b167911723054ac3845fc35c0b11

postgresql scala enums implicit quill
2个回答
0
投票

尝试添加引号

implicit val encode: MappedEncoding[MyEnumType, String] =
  MappedEncoding(x => s"'$x'")
implicit val decode: MappedEncoding[String, MyEnumType] =
  MappedEncoding(s => MyEnumType.withName(s.stripPrefix("'").stripSuffix("'")))

0
投票

问题是默认情况下,Quill 将枚举值生成为

java.sql.Types.VARCHAR
。 因此出现错误
operator does not exist: my_enum_type = character varying
,因为 Postgres 不知道如何将
character varying
转换为我的自定义 Postgres
enum
类型。

解决方案是强制 Quill 将值编码为

java.sql.Types.OTHER
.

object Ctx extends PostgresJdbcContext(SnakeCase)

object MyEnumType extends Enumeration {
  type MyEnumType = Value

  val ONE, TWO, THREE = Value

  import Ctx.*
  
  implicit val enc: Encoder[MyEnumType] = encoder(
    java.sql.Types.OTHER,
    (index, value, row) => row.setObject(index, value.toString, java.sql.Types.OTHER)
  )

  implicit val dec: Decoder[MyEnumType] =
    decoder(row => index => this.withName(row.getObject(index).toString))
}
© www.soinside.com 2019 - 2024. All rights reserved.