Reputation: 1953
Say I have a SQL table with columns x
and y
, each integer valued. I can do a Slick query to select for 5 <= x <= 10
like this:
val myQuery = TableQuery[MyXYTable]
myQuery.filter(p => p.x >= 5 && p.x <= 10)
Now suppose I want to simultaneously filter for 5 <= y <= 10
as well. I'd like to re-use my same filter logic, but this time apply it to the y
column. Is there a way to do this in Slick? ie to write a filter function, and pass in an argument specifying which column it should filter? So I'd have something like:
myQuery.addFiveTenFilter(x-column).addFiveTenFilter(y-column)
If I was writing raw SQL this would be pretty trivial, but I can't see how to do it with Slick syntax.
Upvotes: 4
Views: 548
Reputation: 4411
If you create a function of type Rep[Int] => Rep[Boolean]
, you can use it in a filter
method and pass the column in:
// As a function literal.
val filterByFiveTen: (Rep[Int] => Rep[Boolean]) = { column =>
column >= 5 && column <= 10
}
myQuery.filter(row => filterByFiveTen(row.xColumn))
// As a method.
def filterByFiveTen(column: Rep[Int]): Rep[Boolean] = {
column >= 5 && column <= 10
}
myQuery.filter(row => filterByFiveTen(row.xColumn))
Upvotes: 1