Search code examples
scalascalaquery

Conditionally enhancing ScalaQuery queries


I have a query I'm conditionally enhancing dependent on the presence or absence of count and offset parameters.

val retrieveCustomer: (Option[String], Option[Int], Option[Int]) => List[Customer] = { ( customerId : Option[String], count : Option[Int], offset : Option[Int] ) =>
    val initialQ: Query[CustomerTable.type, Customer] = customerId.map( c => CustomerTable.where(_.id === c) ).getOrElse( CustomerTable.map { c => c } )
    val qPlusOffset = offset.map ( offset => initialQ.drop(offset) ).getOrElse(initialQ)
    val qoPlusLimit = count.map( count => qPlusOffset.take(count) ).getOrElse(qPlusOffset)

    DBGlobal.db.withTransaction { qoPlusLimit.list }

}

I'm curious if there's a more concise way to write this compared to this approach.

Pray tell.


Solution

  • Here's a one liner.

    val qFinal = initialQ.drop(offset.getOrElse(0)).take(count.getOrElse(Int.MaxValue))