How to parameterize Scala Slice queries according to WHERE clause conditions?

Suppose these two simple queries are:

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 duplicate patterns 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 do not know how to achieve it, because there are several implicit transformations for understanding that I have not yet untangled. More specifically: what type ??? => Boolean ??? => Boolean in findBy method?

EDIT

These are the classes of accounts and accounts:

 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 _) } 
0
source share
1 answer

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) 
+4
source

All Articles