0
votes

I'm using Slick 3.0 to access a PostgreSQL database in Play 2.4 and need a way to delete all rows from a table without dropping it.

Deleting single rows works:

lazy val tasks = TableQuery[Tasks]

def delete(id: Long) = db.run(tasks.filter(_.id === id).delete)

But I can't figure out how to implement an empty where clause in slick to delete all rows. (As seen in PostgreSQL documentation)

The trivial solution db.run(tasks.delete) does not seem to do anything and there doesn't seem to be a truncate function available.

Edit:

db.run(tasks.delete) works, you just have to wait for the Future to complete. Truncating a table requires some SQL: db.run(sqlu"TRUNCATE TABLE table_name RESTART IDENTITY;").

1
Notice that db.run returns an future you have to wait for it to completejilen
If you are happy with your solution, please submit it as an answer to this question and accept it.Iain

1 Answers

0
votes

Since you already got the answer, I would like to add that you can also use Await.result function from the scala.concurrent package in case you want to make the program wait for the db query to complete. The query goes something like this:

Await.result(db.run(sqlu"TRUNCATE TABLE table_name RESTART IDENTITY;"),Duration.Inf))