Slick 2.0: Delete multiple rows

倾然丶 夕夏残阳落幕 提交于 2020-01-03 04:46:11

问题


What I wanted to do is delete the N oldest ids from my table using this function:

def deleteOldRows(size: Int)(implicit s: Session): Int =
  MyTable.sortBy(_.id.asc).take(size).delete

This operation throws a SlickException because

A query for a DELETE statement must resolve to a comprehension with a single table -- Unsupported shape: Comprehension(fetch = None, offset = None)

As stated also on the documentation:

A query for deleting must only select from a single table. Any projection is ignored (it always deletes full rows).

What is triggering the multiple table? Is it because the sortBy clause creates a temporary table to store the results? For the moment I rewrote my query to this:

MyTable.sortBy(_.id.asc).take(size).list().map(result => MyTable.filter(_.id === result.id).delete)

Which is basically take the ids and for each one filter and delete, is there a more readable and direct way to delete multiple rows at once?


回答1:


Try MyTable.filter(_.id in MyTable.sortBy(_.id.asc).take(size).map(_.id)).delete. Without looking at the details right now, I am assuming the error message to be misleading and the cause to be ORDER BY and LIMIT to not be supported for DELETE.

I created a ticket: https://github.com/slick/slick/issues/872



来源:https://stackoverflow.com/questions/24475684/slick-2-0-delete-multiple-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!