[英]Scala Slick inserting multiple random rows into PostgreSql database
[英]Using Scala Slick with database enums
使用 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 類型?
看起來您可以使用沒有 pg-slick 的 String 映射到枚舉。
訣竅是向數據庫添加強制轉換,如PG JDBC 問題 1420 中所述:
CREATE CAST (character varying AS WeekDay) WITH INOUT AS ASSIGNMENT
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.