【问题标题】:Slick 3: insertOrUpdate not working光滑 3:插入或更新不起作用
【发布时间】:2017-02-16 14:45:07
【问题描述】:

我在 Postgresql 9.6.1 中使用 slick,Plya! 2.5 和流畅的 2.0.2。

(我也使用 slick-pg 0.14.3,但我认为它不会在这里改变任何东西。)

我以非常直接的方式使用insertOrUpdate,但我仍然遇到一个独特的异常。

我有一个使用insertOrUpdate 的非常简单的测试: 如果我多次运行它,我总是会得到一个 sql 异常:

ERROR: duplicate key value violates unique constraint "ga_client_id_pkey"
  Detail: Key (client_id)=(1885746393.1464005051) already exists

但是,我的表是用client_id 作为主键定义的:

def clientId = column[String]("client_id", O.PrimaryKey)

并在sql中定义如下:

client_id    TEXT NOT NULL UNIQUE PRIMARY KEY

测试的功能只是做:

db.run(gaClientIds.insertOrUpdate(gaClientId))

而控制器只是调用这个方法而不做其他任何事情。

奇怪的是,多次启动方法本身不会导致错误,但控制器会导致错误,尽管它只是调用方法。

insertOrUpdate slick 功能还不确定还是我遗漏了什么?

【问题讨论】:

  • slick3.2.1 我这边也有同样的问题。 @Simon 你找到解决方案了吗?
  • 不,不幸的是,我发现的唯一解决方案是用普通 sql 编写数据库调用...
  • 这也是我的解决方案
  • 就我而言,有时会被保存,有时会失败。我无法在本地复制它,尽管在上层环境中使用相同的库和版本,有时它在生产中甚至会达到平衡。

标签: postgresql slick upsert


【解决方案1】:

insertOrUpdate 仅在 MySQL 驱动中支持

http://slick.lightbend.com/doc/3.2.1/supported-databases.html

你可以试试这个库,它为你提供了 insertOrUpdate/upsert 的实现

https://github.com/tminglei/slick-pg

这就是我们在当前项目中使用它的方式。

import com.github.tminglei.slickpg._
import com.typesafe.config.ConfigFactory
import slick.basic.Capability

object DBComponent {

  private val config = ConfigFactory.load()

  val driver = config.getString("rdbms.properties.driver") match {
    case "org.h2.Driver" => slick.jdbc.H2Profile
    case _               => MyPostgresProfile
  }

  import driver.api._

  val db: Database = Database.forConfig("rdbms.properties")

}

trait MyPostgresProfile extends ExPostgresProfile {

  // Add back `capabilities.insertOrUpdate` to enable native `upsert` support; for postgres 9.5+
  override protected def computeCapabilities: Set[Capability] =
    super.computeCapabilities + slick.jdbc.JdbcCapabilities.insertOrUpdate

  override val api: MyAPI.type = MyAPI

  object MyAPI extends API
}

object MyPostgresProfile extends MyPostgresProfile

【讨论】:

  • IMO,该文档让我们认为每个驱动程序都支持它,而我以前从未见过此页面。感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-13
相关资源
最近更新 更多