Search code examples
scalaslick

Optional pagination


I am trying to implement simple db query with optional pagination. My try:

def getEntities(limit: Option[Int], offset: Option[Int]) = {

  // MyTable is a slick definition of the db table 

  val withLimit = limit.fold(MyTable)(l => MyTable.take(l))    // Error here. 
                                                               // Mytable and MyTable.take(l) 
                                                               // has various types
  val withOffset = offset.fold(withLimit)(o => withLimit.drop(o))
  val query = withOffset.result

  db.run(query)
}

The problem is an error:

type mismatch:
found: slick.lifted.Query
required: slick.lifted.TableQuery

How to make this code runnable? And maybe a little bit prettier?


My current fix to get Query from TableQuery is to add .filter(_ => true), but IMHO this is not nice:

val withLimit = limit.fold(MyTable.filter(_ => true))(l => MyTable.take(l))

Solution

  • Try to replace

    val MyTable = TableQuery[SomeTable]
    

    with

    val MyTable: Query[SomeTable, SomeTable#TableElementType, Seq] = TableQuery[SomeTable]
    

    i.e. to specify the type (statically upcast TableQuery to Query).