How to get pagination select on slick + postgresql

In a postgresql database, with spot 3, what's the best way to have pagination?

  • get all rows and pagination using scala (doesn't seem to be very efficient)?
  • static query with restriction and offset?
  • Is there another way?
+6
source share
2 answers

You can use the take and drop methods on TableQuery objects. They will be translated to limit and offset as a result of the SQL query:

 val users: TableQuery[UsersTable] = UsersTable.query val firstPartOfUsers = users.drop(0).take(25).result val secondPartOfUsers = users.drop(25).take(25).result 

These two actions will be translated into the following SQL queries:

 select "name", "email", "id" from "users" limit 25 offset 0 select "name", "email", "id" from "users" limit 25 offset 25 
+9
source

I agree with @Pawel, and I think the following example is more detailed as you want:

 object Paging { case class PageReq( page: Int = 1, size: Int = DefaultPageSize, sortFields: Option[List[String]] = None, sortDirections: Option[List[String]] = None) { def offset = (page - 1) * size } case class PageRes[T](items: Seq[T], total: Long) } UsersDao { val users: TableQuery[UsersTable] = UsersTable.query def findBySomeParam(params: A, pageReq: PageReq): Future[PageRes[User]] = { db.run(users.result) .filter(params) .map { r => PageRes(items = r.slice(pageReq.offset, pageReq.offset + pageReq.size), total = r.size) } } } 
-2
source

All Articles