How can I apply a filter by default on a Slick TableQuery object?

552 views Asked by At

In slick I have a setup that looks sort of like this:

class Users(tag: Tag) extends Table(tag) {
  def name = column[String]
  def disabled = column[Boolean]
  def * = ...
}

object Users extends TableQuery(new Users(_)) {}

What I want is anytime someone uses the Users object to query the database, it excludes disabled users. For example:

Users.where(_.name === "Fred")

executes:

select * from users where name = 'Fred' and disabled = false

Is this possible? I can't seem to find anything in the TableQuery object to override to let me do this.

Appreciate any light that can be shed on this.

1

There are 1 answers

0
Regis Blanc On

One thing you should be able to do is to define your queries as simple Scala expressions/functions:

val disabledUsers = Users.filterNot(_.disabled)

The above only defines a query that will filter out disabled people. You can then combine it several time at different program points with more specific queries:

disabledUsers.where(_.name === "Fred")

I believe Slick should then be smart enough to compile and optimize the query into a single SELECT