-->

斯卡拉ANORM PostgreSQL的错误当存储字节数组(Scala Anorm Postgres

2019-09-21 07:57发布

我在斯卡拉Playframework数据库表定义为

CREATE TABLE account (
    id     SERIAL,
    email  TEXT  NOT NULL,
    buffer BYTEA NOT NULL,
    PRIMARY KEY (id)
);

我使用的协议缓冲器将对象序列为一个字节数组用下面的代码

DB.withConnection{ implicit c=>
  SQL("INSERT INTO device (buffer,secret) VALUES ({secret},{buffer})").on(
    "secret"->device.getSecret(),
    "buffer"->device.toByteArray()
  ).executeInsert()
}

由返回的类型device.toByteArray()Array[Byte] ,其匹配该列的数据库类型。 但是在执行的代码中,我得到

play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[PSQLException: ERROR: column "buffer" is of type bytea but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
  Position: 44]]
    at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:134) [play_2.9.1.jar:2.0.3]
    at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:115) [play_2.9.1.jar:2.0.3]
    at akka.actor.Actor$class.apply(Actor.scala:318) [akka-actor.jar:2.0.2]
    at play.core.ActionInvoker.apply(Invoker.scala:113) [play_2.9.1.jar:2.0.3]
    at akka.actor.ActorCell.invoke(ActorCell.scala:626) [akka-actor.jar:2.0.2]
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:197) [akka-actor.jar:2.0.2]
Caused by: org.postgresql.util.PSQLException: ERROR: column "buffer" is of type bytea but expression is of type character varying

Answer 1:

纵观ANORM源和Postgres的文档 ,它看起来像你需要添加一个处理存储Array[Byte]正确使用setBytes代替setObject ,它在当前代码要求。

我在anyParameter延长赛的框架阅读

    value match {
      case Some(bd: java.math.BigDecimal) => stmt.setBigDecimal(index, bd)
      case Some(b: Array[Byte]) => stmt.setBytes(index, b)
      case Some(o) => stmt.setObject(index, o)
      // ...

并添加

implicit val byteArrayToStatement = new ToStatement[Array[Byte]] {
  def set(s: java.sql.PreparedStatement, index: Int, aValue: Array[Byte]): Unit = setAny(index, aValue, s)
}

你应该可能能够通过类型类魔法在工作中要做到这一点框架之外的以及在这里,但我没有时间去弄清楚现在。



文章来源: Scala Anorm Postgresql Error When Storing Byte Array