Search code examples
scalascalaqueryslick

How to parametrize Scala Slick queries by WHERE clause conditions?


Assume these two simple queries:

def findById(id: Long): Option[Account] = database.withSession { implicit s: Session =>
  val query = for (a <- Accounts if a.id === id) yield a.*
  query.list.headOption
}

def findByUID(uid: String): Option[Account] = database.withSession { implicit s: Session =>
  val query = for (a <- Accounts if a.uid === uid) yield a.*
  query.list.headOption
}

I would like to rewrite it to remove the boilerplate duplication to something like this:

def findBy(criteria: ??? => Boolean): Option[Account] = database.withSession {
  implicit s: Session =>
    val query = for (a <- Accounts if criteria(a)) yield a.*
    query.list.headOption
}

def findById(id: Long) = findBy(_.id === id)

def findByUID(uid: Long) = findBy(_.uid === uid)

I don't know how to achieve it for there are several implicit conversions involved in the for comprehension I haven't untangled yet. More specifically: what would be the type of ??? => Boolean in the findBy method?

EDIT

These are Account and Accounts classes:

case class Account(id: Option[Long], uid: String, nick: String)

object Accounts extends Table[Account]("account") {
  def id = column[Option[Long]]("id")
  def uid = column[String]("uid")
  def nick = column[String]("nick")
  def * = id.? ~ uid ~ nick <> (Account, Account.unapply _)
}

Solution

  • I have this helper Table:

    abstract class MyTable[T](_schemaName: Option[String], _tableName: String) extends Table[T](_schemaName, _tableName) {
      import scala.slick.lifted._
      def equalBy[B: BaseTypeMapper]
        (proj:this.type => Column[B]):B => Query[this.type,T] = { (str:B) => 
         Query[this.type,T,this.type](this) where { x => proj(x) === str} }
    
    }
    

    Now you can do:

     val q=someTable.equalBy(_.someColumn) 
     q(someValue)