【问题标题】:Slick 3.1.x Insert all details from one master to the other, transactionally?Slick 3.1.x 以事务方式将所有细节从一个主节点插入到另一个主节点?
【发布时间】:2016-12-20 22:26:25
【问题描述】:

我有一个有趣的用例。基本上我有一个需要合并的sourceUser: UserRow 和targetUser: UserRow。合并意味着将sourceUser 标记为不活动并将所有源链接帐户(详细信息)复制到目标用户。所有缺失的细节,例如UserRow slick 生成的类型等可以签出in this github project。

我可以在 SQL 中做到这一点没问题,例如

UPDATE "user" SET active=false WHERE user_id=${sourceUserId};
INSERT INTO linked_account(user_id, provider_key, provider_hashed) 
   SELECT ${targetUserId}, provider_key, provider_hashed
   FROM linked_account 
   WHERE user_id=${sourceUserId}

我的 Slick 尝试混合了通用 dao 和无法了解如何以事务方式编写的 slick action。我也找不到同时选择和插入的方法,即此尝试无法编译:

def merge(targetUser: UserRow, sourceUser: UserRow) : Future[Unit] = {
  // deactivate the source user
  update(sourceUser.copy(active = false))

  val action = (for {
    // get the linked accounts to source 
    linkedAccountSource <- LinkedAccount
    // match the source user
    source <- User if source.id === sourceUser.id && linkedAccountSource.userId === source.id
    // insert into target the previously matched source linked 
    // account but having target user as user_id
    // ........................................ doesn't compile here VVVVVVVVVVVVVVVVVVVVVVV
    linkedAccountTarget <- (LinkedAccount += linkedAccountSource.copy(userId = targetUser.id))
    // match the target user attempting to update set active=false
    target <- User if target.id === targetUser.id
  } yield linkedAccountTarget).transactionally
  db.run(action)
}

更新我到此为止,但最后一个编译器错误,基本上是想将targetUser.id 分配给sourceUser.id 的链接帐户结果

def merge(targetUser: UserRow, sourceUser: UserRow) : Future[Unit] = {
  // define an update DBIOAction to deactivate sourceUser
  val updateAction = User.filter(_.id === sourceUser.id).update(sourceUser.copy(active = false))

  // selects all linkedAccount from sourceUser but yield the userId of the targetUser
  val selectAction = (for {
    linkedAccount <- LinkedAccount
    user <- User if user.id === sourceUser.id && user.id === linkedAccount.userId
  } yield (targetUser.id, linkedAccount.providerKey, linkedAccount.providerPassword, linkedAccount.modified)).result

  // define an insert DBIOAction to insert all the selected linked accounts from sourceUser to targetUser
  val insertAction = selectAction.flatMap(LinkedAccount ++= _)

  // combine both actions using >> and transactionally
  db.run((updateAction >> insertAction).transactionally).map(_ => ())
}

最后一个错误,我尝试在不同的地方做.as[LinkedAccountRow],但它不会喜欢它:

[error] /home/bravegag/code/play-authenticate-usage-scala/app/dao/UserDao.scala:101: type mismatch;
[error]  found   : Seq[(Long, String, String, Option[java.sql.Timestamp])]
[error]  required: Iterable[generated.Tables.LinkedAccountRow]
[error]       val insertAction = selectAction.flatMap(LinkedAccount ++= _)
[error]                                                                 ^

【问题讨论】:

    标签: sql scala slick


    【解决方案1】:

    如果您只是更改此设置,这一切都不会奏效吗:

    ...
    } yield (targetUser.id, linkedAccount.providerKey, linkedAccount.providerPassword, linkedAccount.modified)).result
    ...
    

    到这些方面:

    ...
    } yield (targetUser.id, linkedAccount.providerKey, linkedAccount.providerPassword, linkedAccount.modified)).result
    .map(LinkedAcount.tuppled)
    ...
    

    您还可以使用一个巧妙的技巧在一个SQL 操作中执行INSERT...SELECT。这将模仿您想要的 SQL:

    INSERT INTO linked_account(user_id, provider_key, provider_hashed) 
    SELECT ${targetUserId}, provider_key, provider_hashed
    FROM linked_account 
    WHERE user_id=${sourceUserId}
    

    应该是这样的:

    LinkedAccount
          .map(acc => (acc.userId, acc.prividerKey, providerHashed))
          .forceInsertQuery(
               for {
                    acc <- LinkedAccount if acc.userId === sourceUser.id
                } yield (acc))
                .map(acc => 
                    (acc.userId, acc.privderKey, acc.providerHashed))
           )
    

    这个forceInsertQuery 显然是这里的关键。只要它最终产生与原始map(forceInsertQuery 之前的那个)匹配的投影,您基本上可以在其中包含您想要的任何内容(例如具有多个连接的查询等)。

    补充说明: 因为forceInsertQuery 里面的东西实际上是一个普通的Query,你可以做例如预编译。这将是这样的:

    // this would need to be obviously created once, perhaps in your DAO
    // as member value
    private val query = Compiled(sourceUserId: Rep[Long] => (for {
        acc <- LinkedAccount if acc.userId === sourceUserId
    } yield (acc))
        .map(acc => 
            (acc.userId, acc.privderKey, acc.providerHashed)
        )
    )
    ...
    // and inside your method
    LinkedAccount
          .map(acc => (acc.userId, acc.prividerKey, providerHashed))
          .forceInsertQuery( query(sourceUser.id) )
    

    【讨论】:

    • 很棒的答案帕维尔!太感谢了!如果您能就性能方面的内容发表一下意见,我将不胜感激。
    • 这里有两个性能级别(至少):1)DB - 不能说太多,因为它可能取决于您的数据库,但您通常会在此处保存数据库往返,这应该是一些东西. 2) Slick - 如果您关心 Slick 编译性能,您可以预编译查询部分(我用预编译示例更新了答案)
    • 嗨,Pawel,.map(LinkedAcount.tuppled) 不起作用。首先是tupled,其次我按照您的建议尝试使用生成的 TableQuery LinkedAccount 并且不起作用。我也尝试使用 LinkedAccountRow 并且也不起作用。我搜索了有关如何使用元组、应用、取消应用、 的示例,但没有发现任何可以修复编译器错误的东西...
    • 啊,它的工作原理是这样的:yield (targetUser.id, linkedAccount.providerKey, linkedAccount.providerPassword, linkedAccount.modified)).result.map(_.map(LinkedAccountRow.tupled)) 有比双映射更简单的替代方案吗?
    【解决方案2】:

    我现在正在打电话,但我认为您应该在列元组上使用 &lt;&gt; 运算符而不是 as[LinkedAccountRow]。

    &lt;&gt; 将在列元组和目标对象之间转换的函数对作为两个参数。对于案例类,这是apply.tupled、unapply 函数。

    最合适的地方应该是在selectAction 理解的yield 子句中。

    【讨论】:

      猜你喜欢
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 2012-03-12
      • 2017-05-15
      • 2019-12-03
      • 2018-07-13
      • 1970-01-01
      相关资源
      最近更新 更多