osocron osocron - 3 months ago 25
Scala Question

How to abstract a query by predicate in Scala using Slick

I'm finding a repetitive pattern in my code and I would like to abstract over it, however I can't seem to get it right. The code that I would like to abstract is something like this:

def queryByPredicate(p: (OAuthClientTable => Rep[Boolean])): Future[Option[OAuthClient]] = {
val query = oAuthClientTableQuery.filter(p)
db.run(query.result.headOption)
}


I tried something like this:

def queryByPredicate[A, B](p: (A => Rep[Boolean]), t: TableQuery[A]): Future[Option[B]] = {
val query = t.filter(p)
db.run(query.result.headOption)
}


However the compiler complains with the following error:

Error:(132, 25) type mismatch;
found : slick.profile.SqlAction[Option[A#TableElementType],slick.dbio.NoStream,slick.dbio.Effect.Read]
required: slick.dbio.DBIOAction[Option[B],slick.dbio.NoStream,Nothing]
db.run(query.result.headOption)


And honestly, I have no idea how to create a generic
Option[A#TableElementType]

Answer
def queryByPredicate[A <: Table[B], B](p: (A => Rep[Boolean]), t: TableQuery[A]): Future[Option[B]] = {
  val query = t.filter(p)
  db.run(query.result.headOption)
}
Comments