3

次のように定義されたScala 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
4

1 に答える 1

4

anorm ソースPostgres docsを見ると、現在のコードが呼び出している の代わりに をArray[Byte]使用して適切に保存するためのハンドラを追加する必要があるようです。setBytessetObject

フレームワークの 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)
}

フレームワークの外でも、ここで動作している型クラスの魔法を介してこれを実行できる可能性がありますが、今はそれを理解する時間がありません。

于 2012-08-17T07:16:32.993 に答える