Scala 2.13中如何在Quill中正确使用Postgres枚举类型?
解决方案
方案1:使用Quill原生QuillEnum宏(推荐,Quill 3.x+)
Quill提供的QuillEnum宏可以自动生成适配PostgreSQL枚举的编码器/解码器,无需手动实现转换逻辑:
import io.getquill.QuillEnum @QuillEnum object MyEnumType extends Enumeration { type MyEnumType = Value val ONE, TWO, THREE = Value } // 在Quill上下文使用时导入枚举的隐式编码器 val ctx = new SqlMirrorContext(PostgresDialect, SnakeCase) import ctx._ import MyEnumType._ // 查询示例 val query = quote { query[MyTable].filter(_.column1 == MyEnumType.ONE) }
生成的SQL会自动转为:WHERE column_1 = 'ONE'
方案2:手动实现Encoder/Decoder(兼容旧版Quill)
如果使用Quill 2.x或需要自定义逻辑,可手动实现编码器和解码器,确保枚举值被正确转换为PostgreSQL可识别的格式:
import io.getquill.{Encoder, Decoder, PostgresDialect, SqlMirrorContext} object MyEnumType extends Enumeration { type MyEnumType = Value val ONE, TWO, THREE = Value // 自定义编码器:将枚举值转为字符串,指定SQL类型为数据库实际枚举类型名 implicit val encoder: Encoder[MyEnumType] = Encoder.stringEncoder .contramap(_.toString) .sqlType("my_enum_type") // 替换为你数据库中的枚举类型名 // 自定义解码器:从字符串还原枚举值 implicit val decoder: Decoder[MyEnumType] = Decoder.stringDecoder .map(MyEnumType.withName) } // 使用示例 val ctx = new SqlMirrorContext(PostgresDialect, SnakeCase) import ctx._ import MyEnumType._ val query = quote { query[MyTable].filter(_.column1 == MyEnumType.TWO) }
方案3:使用Enumeratum库
若选择用Enumeratum替代Scala原生枚举,需正确集成Quill支持:
import enumeratum._ import io.getquill._ sealed trait MyEnumType extends EnumEntry object MyEnumType extends Enum[MyEnumType] with QuillEnum[MyEnumType] { override val values = findValues case object ONE extends MyEnumType case object TWO extends MyEnumType case object THREE extends MyEnumType } // 使用时导入枚举的隐式转换 val ctx = new SqlMirrorContext(PostgresDialect, SnakeCase) import ctx._ import MyEnumType._ val query = quote { query[MyTable].filter(_.column1 == ONE) }
注意事项
- 确保数据库中的枚举类型名与代码中指定的一致;
- 隐式编码器/解码器需在Quill上下文的作用域内可见;
- 可通过
ctx.translate(query)调试生成的SQL,确认枚举值格式是否正确。
内容的提问来源于stack exchange,提问作者daharon
相关产品推荐
相关产品推荐

