PostgreSQL jsonb更新多个嵌套字段

时间:2018-11-22 09:17:58

标签: sql postgresql scala scalikejdbc

在postgresql数据库中具有id字段和jsonb字段的I表。 jsonb的结构看起来像这样:

{
    "id": "some-id",
    "lastUpdated": "2018-10-24T10:36:29.174Z",
    "counters": {
        "counter1": 100,
        "counter2": 200
    }
}

我需要做的是更新lastModified和其中一个计数器:

def update(id: String, counter: Option[String])

例如,如果我执行update("some-id", Some("counter2")),则需要将lastUpdated作为当前日期时间,并将counter2递增到201

我正在使用ScalikeJDBC,这是我到目前为止的去处:

def update(id: String, counter: Option[String]): Option[ApiKey] = DB localTx { implicit session =>

val update =
  if(counter.isDefined)
    sqls"""'{"lastUpdated": ${DateTime.now()}, "counters": {'${counter.get}: COALESCE('counters'->>${counter.get},'0')::int'}'"""
  else
    sqls"""'{"lastUpdated": ${DateTime.now()}}'"""

sql"UPDATE apiKey SET content = content || $update WHERE id = $key".update().apply()
}

但是出现以下错误:

org.postgresql.util.PSQLException: The column index is out of range: 4, number of columns: 3

我尝试了其他方法,但是无法使其起作用。可以将其写为单个查询吗?

这里有个小提琴,可以帮助测试https://www.db-fiddle.com/f/bsteTUMXDGDSHp32fw2Zop/1

1 个答案:

答案 0 :(得分:1)

我对PostgreSQL的jsonb类型了解不多,但是似乎不可能将所有内容作为绑定参数传递给JDBC PreparedStatement。我不得不说,您可能必须使用SQLSyntax.createUnsafely绕过PreparedStatement,如下所示:

def update(id: String, counter: Option[String]): Unit = DB localTx { implicit session =>
  val now = java.time.ZonedDateTime.now.toOffsetDateTime.toString
  val q: SQLSyntax = counter match { 
    case Some(c) => 
      val content: String =
        s"""
        jsonb_set(
            content || '{"lastUsed": "${now}"}',
            '{counters, $c}',
            (COALESCE(content->'counters'->>'$c','0')::int + 1)::text::jsonb
        )
        """
      SQLSyntax.createUnsafely(s"""
    UPDATE
        example
    SET
        content = ${content}
    WHERE
        id = '$id';
    """)
    case _ => 
      throw new RuntimeException
  }
  sql"$q".update.apply()
}
update("73c1fa11-bf2f-42c9-80fd-c70ac123fca9", Some("counter2"))