2012-08-17 47 views
3

我具有如斯卡拉ANORM PostgreSQL的錯誤時存儲字節數組

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() 
} 
定義Scala中Playframework數據庫表

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

望着anorm sourcePostgres docs,它看起來像你需要添加一個處理使用setBytes代替setObject,它在當前代碼要求妥善儲存Array[Byte]

我會延長比賽中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) 
} 

您應該可能能夠通過類型類做這個框架之外還有在這裏工作有魔力,但我現在沒有時間弄清楚。

+0

哇這是一個了不起的答案。我注意到,如果我對'secret'進行了硬編碼,並且_only_傳遞了成功的'Array [Byte]'參數。這感覺就像一個錯誤,你的評論會加強這個想法。 – 2012-08-17 07:29:39