我需要执行一些查询,这些查询可能依赖于通过REST接口提供的外部参数。例如,客户端可能需要表单的URL
some/entities?foo=12&bar=17参数,比如foo、bar和quux都是可选的。因此,我从使用Squeryl设计一些查询开始,例如
object Entity {
def byFoo(id: Long) = from(DB.entities)(e =>
where(e.foo === id)
select(e)
)
// more criteria
}当然,我希望避免出现组合爆炸,所以我只设计了三个查询,这些查询可能会从另一个查询中获取数据:
object Entity {
def byFoo(id: Long, source: Query[Entity] = DB.entites) = from(source)(e =>
where(e.foo === id)
select(e)
)
def byBar(id: Long, source: Query[Entity] = DB.entites) = from(source)(e =>
where(e.bar === id)
select(e)
)
// more criteria
}现在我可以将它们组合起来,并运行一个查询,如
val result = Entity.byFoo(12,
source = Entity.byBar(17)
)这种方法的唯一问题是后台Squeryl将生成子查询,这可能是效率低下的。使用更典型的查询生成器,我将能够组合这些查询并获得以下等价内容:
from(DB.entities)(e =>
where(
e.foo === 12 and
e.bar === 17
)
select(e)
)有没有一种不同的方法来动态组合Squeryl中的查询,从而导致这种更有效的形式?
发布于 2012-11-23 21:45:02
我认为您应该研究的第一件事是inhibitWhen,您可以找到在文件中。它的要点是将查询建模如下:
var foo: Option[Int] = None
var bar: Option[Int] = None
from(DB.entities)(e =>
where(
e.foo === foo.? and
e.bar === bar.?)
select(e))那个?第一个表达式中的运算符等效于(e.foo === foo).inhibitWhen(foo == None)
https://stackoverflow.com/questions/13515398
复制相似问题