【问题标题】:Using Scala Slick with database enums将 Scala Slick 与数据库枚举一起使用
【发布时间】:2020-02-24 15:19:56
【问题描述】:

使用 Slick 3 和 PostgreSQL,我需要查询和更新具有枚举类型列的表:

create type WeekDay as ENUM('sun','mon','tue','wed','thu','fri','sat');

create table shifts(
    id serial PRIMARY KEY,
    user_id INTEGER,
    branch_id INTEGER,
    start INTEGER,
    duration INTEGER,
    day WeekDay
    -- foreign keys etc.
);

我尝试使用 Slick 的 MappedColumnType[java.time.DayOfWeek,String],但这不能满足 Postgres 的类型检查器(TBH,正确):

org.postgresql.util.PSQLException: ERROR: column "day" is of type weekday but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
  Position: 92
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2412)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2125)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:297)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:169)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:136)
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
    at slick.jdbc.JdbcActionComponent$InsertActionComposerImpl$SingleInsertAction.$anonfun$run$15(JdbcActionComponent.scala:520)

表类:

class ShiftTable(tag:Tag) extends Table[Shift](tag, "shifts") {
  import Mappers.dayOfWeekMapper
  def id = column[Long]("id", O.AutoInc, O.PrimaryKey)
  def userId = column[Long]("user_id")
  def branchId = column[Long]("branch_id")
  def start = column[Int]("start")
  def duration = column[Int]("duration")
  def day = column[DayOfWeek]("day")    // <- problematic column

  // keys etc/
  def * = (id, userId, branchId, start, duration, day) <> (Shift.tupled, Shift.unapply)
}

如何将 Scala 值映射到自定义 PostgreSQL 类型?

【问题讨论】:

  • 看起来有人已经遇到了同样的问题:stackoverflow.com/questions/22945485/…
  • 谢谢!我正在其他项目中使用 slick-pg,但我希望有一个不需要额外库的解决方案,因为我认为这个问题足够小,可以在本地解决:-(

标签: postgresql scala slick slick-3.0


【解决方案1】:

看起来您可以使用不带 pg-slick 的字符串映射到枚举。

诀窍是向数据库添加演员表,如 PG JDBC Issue 1420 中所述:

CREATE CAST (character varying AS WeekDay) WITH INOUT AS ASSIGNMENT

documentation for CAST 描述了WITH INOUT(避免编写转换函数)和AS ASSIGNMENT(在赋值时隐式应用转换)。

然后您可以使用MappedColumnType.base[java.time.DayOfWeek, String] 来定义从列到DayOfWeek 的映射。

我在这里放置了一个可运行的示例:https://github.com/d6y/pg-enum/blob/master/src/main/scala/main.scala

【讨论】:

    猜你喜欢
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多