【问题标题】:Rewrite this SQL query using scala slick使用 scala slick 重写此 SQL 查询
【发布时间】:2020-09-18 01:45:18
【问题描述】:
class ItemTable(tag: Tag) extends Table[Item](tag, _tableName = "items") {

  def id: Rep[Int] = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def authId: Rep[String] = column[String]("auth_id")
  def productId: Rep[Int] = column[Int]("product_id")
  def position: Rep[Int] = column[Int]("position")

  override def * : ProvenShape[Item] = (id, authId, productId, position) <> ((Item.apply _).tupled, Item.unapply)
}


class ItemService @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext) {

    private lazy val query = TableQuery[ItemTable]
    def updateItem(item: Item, previousPosition: Int): Future[Item] = {

        if (previousPosition < item.position) {
          // this is the sql I want to convert to slick
          db.run(sqlu""" UPDATE #${query.baseTableRow.tableName} SET position = position - 1 WHERE position >= #$previousPosition AND position <= #${item.position} AND auth_id = '#${item.authId}'""")
        }
        else if (previousPosition > item.position) {
          db.run(sqlu""" UPDATE #${query.baseTableRow.tableName} SET position = position + 1 WHERE position <= #$previousPosition AND position >= #${item.position} AND auth_id = '#${item.authId}' """)
        }
        else {
         // some other code
        }
    }
}

case class Item(id: Int, authId: String, productId: Int, position: Int){}

我的 SQL 工作正常,我被困在这里,将它翻译成光滑的。

val q2 = query.filter(f=> f.authId === item.authId && f.position >= previousPosition && f.position <= item.position)

// 不知道怎么更新多个或者把结果集传给更新函数

【问题讨论】:

    标签: mysql scala slick


    【解决方案1】:

    Slick 的嵌入样式不支持SET position = position + 1 (Slick issue 497) 形式的动态变异批量更新。

    这意味着使用您已有的普通 SQL 样式是正确的方法。

    关于惯用 sqlu 的附加说明:我注意到 sqlu 使用“拼接”(#$ 表示表名)。这可以防止 Slick 将值视为字符串,这适合您正在做的事情。但是后来的用法#$previousPosition 更典型地写成一个普通的替换,$previousPosition。那是因为您通常希望 Slick 正确地转义那里的 SQL 参数。它可能对整数没有影响,但对其他数据类型可能。

    【讨论】:

    • 我开始明白为什么 scala 开发人员更喜欢原始 sql 而不是 slick。
    猜你喜欢
    • 2016-12-26
    • 2016-11-21
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2021-01-29
    • 2015-02-04
    相关资源
    最近更新 更多