有条件地增强ScalaQuery查询
我有一个查询,我正在根据计数和偏移参数的存在与否有条件地增强它有条件地增强ScalaQuery查询,scala,scalaquery,Scala,Scalaquery,我有一个查询,我正在根据计数和偏移参数的存在与否有条件地增强它 val retrieveCustomer: (Option[String], Option[Int], Option[Int]) => List[Customer] = { ( customerId : Option[String], count : Option[Int], offset : Option[Int] ) => val initialQ: Query[CustomerTable.type, Cus
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 }
}
我很好奇,与这种方法相比,是否有更简洁的方法来写这篇文章
请告诉我 写这篇文章有什么意义
val retrieveCustomer: (Option[String], Option[Int], Option[Int]) => List[Customer] = { ( customerId : Option[String], count : Option[Int], offset : Option[Int] )
当你可以写这样的东西时:
def getCustomer(id: String, count: Option[Int], offset: Option[Int]): List[Customer]
这显然更简洁,尽管可能与您追求的简洁无关。我倾向于在for{…}块中的每个操作上使用右投影,“失败的”左结果执行基本查询或非完全优化查询,成功的右结果执行完整的drop+take优化
def getCustomer(id: String, count: Option[Int], offset: Option[Int]): List[Customer] = {
val base = Customers.createFinder(_.id)
val q = for{
cust <- base(id) toRight( List[Customer]() )
dropped <- cust.drop(offset) toRight(cust)
taken <- dropped.take(count) toRight(dropped)
} yield taken
DBGlobal.db.withTransaction { q.list map { _.fold(_,_) } }
}
它会为底层DBMS生成一个有效的预处理语句
当然,你所拥有的东西对一次性案件来说很有用。就我个人而言,我正在挖掘{}+任何一个正确的预测,既可以吃你的蛋糕,也可以吃你的蛋糕——也就是说,获得失败点的左结果和成功的右结果,而不是通过{…}选项,它只会产生一个成功的事件,完全不提供关于哪一步实际出错的信息。这里有一条直线
val qFinal = initialQ.drop(offset.getOrElse(0)).take(count.getOrElse(Int.MaxValue))
val qFinal = initialQ.drop(offset.getOrElse(0)).take(count.getOrElse(Int.MaxValue))