加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如果在Slick 3.0.0中不存在,则插入

发布时间:2020-12-16 09:30:04 所属栏目:安全 来源:网络整理
导读:我试图插入,如果不存在,我发现 this post为1.0.1,2.0。 我在the docs of 3.0.0发现交易使用的片段 val a = (for { ns - coffees.filter(_.name.startsWith("ESPRESSO")).map(_.name).result _ - DBIO.seq(ns.map(n = coffees.filter(_.name === n).delete
我试图插入,如果不存在,我发现 this post为1.0.1,2.0。

我在the docs of 3.0.0发现交易使用的片段

val a = (for {
  ns <- coffees.filter(_.name.startsWith("ESPRESSO")).map(_.name).result
  _ <- DBIO.seq(ns.map(n => coffees.filter(_.name === n).delete): _*)
} yield ()).transactionally

val f: Future[Unit] = db.run(a)

如果不存在此结构,我正在努力从insert写入逻辑。我是新来的Slick,并没有Scala的经验。这是我尝试插入,如果不存在于事务外…

val result: Future[Boolean] = db.run(products.filter(_.name==="foo").exists.result)
result.map { exists =>  
  if (!exists) {
    products += Product(
      None,productName,productPrice
    ) 
  }  
}

但是如何把它放在交易区块?这是我能走的最远的地方

val a = (for {
  exists <- products.filter(_.name==="foo").exists.result
  //???  
//    _ <- DBIO.seq(ns.map(n => coffees.filter(_.name === n).delete): _*)
} yield ()).transactionally

提前致谢

解决方法

可以使用单个插入…如果不存在查询。这避免了多个数据库往返和竞争条件(事务可能不足以取决于隔离级别)。

def insertIfNotExists(name: String) = users.forceInsertQuery {
  val exists = (for (u <- users if u.name === name.bind) yield u).exists
  val insert = (name.bind,None) <> (User.apply _ tupled,User.unapply)
  for (u <- Query(insert) if !exists) yield u
}

Await.result(db.run(DBIO.seq(
  // create the schema
  users.schema.create,users += User("Bob"),insertIfNotExists("Bob"),insertIfNotExists("Fred"),// print the users (select * from USERS)
  users.result.map(println)
)),Duration.Inf)

输出:

Vector(User(Bob,Some(1)),User(Bob,Some(2)),User(Fred,Some(3)))

生成的SQL:

insert into "USERS" ("NAME","ID") select ?,null where not exists(select x2."NAME",x2."ID" from "USERS" x2 where x2."NAME" = ?)

Here’s the full example on github

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读