更新ScalikeJDBC中的返回查询

问题描述 投票:0回答:1

在范围内有implicit val session: DBSession,具体地说是scalikejdbc.AutoSession

更新工作

sql"""
    update payments set status=${status.name} where id in ($ids)
""".update().apply()

并选择工作

sql"""
   select id
   from payments
   where status='valid'
""".map(_.long).list().apply()

但更新返回列失败,因为事务被设置为只读。

sql"""
  update payments
  set status='submitted'
  where status='pending'
  and scheduled <= ${ZonedDateTime.now.toInstant}
  returning id
""".map(_.long).iterable().apply().toIterator

org.postgresql.util.PSQLException: ERROR: cannot execute UPDATE in a read-only transaction

sessionSQLToResult内部匹配,假设它应该只读:

  case AutoSession | ReadOnlyAutoSession => DB.readOnly(f)

我已经尝试创建自己的DBSession以避免匹配这种模式,但放弃了这种方法。我最接近它的工作是:

val writeableSession: DBSession = DBSession(session.connection, isReadOnly = false)

def inner()(implicit session: DBSession): Iterator[Payment] = {
  sql"""
  update payments
  set status='submitted'
  where status='pending'
  returning id
""".map(_.long).iterable().apply().toIterator
}

inner()(writeableSession)

这失败了因为session.connectionnull

我如何强制将其作为localTx而不是readOnly?

scala scalikejdbc
1个回答
1
投票

通常,AutoSession表现为DDL的自动提交会话和插入/更新/删除操作,而它作为选择查询的只读会话。

它似乎做得如下是直截了当的方式。

DB.localTx { implicit session =>
  // Have both the update operation and select query inside this block
}
© www.soinside.com 2019 - 2024. All rights reserved.