How to parametrize Scala Slick queries by WHERE clause conditions?

廉价感情. 提交于 2019-12-06 17:07:37

问题


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 _)
}

回答1:


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)


来源:https://stackoverflow.com/questions/14334634/how-to-parametrize-scala-slick-queries-by-where-clause-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!