2

I have a method which return a Query:

def list:Query[User] = from(users)(u => where(u.age>20) select(u))

Now I want to count the list, but this method:

list.count(_ => true)

will get and loop all elements in the list.

I want to find a solution to make a "select count" statement from the Query[User], but not found yet.

Or I have to write another method for count:

def countList: Long = from(users)(u => where(u.age>20) compute(count))

Which is not what I want.

Freewind
  • 193,756
  • 157
  • 432
  • 708

3 Answers3

2

Try to compose the two queries:

from(list)(_ => compute(count))
Freewind
  • 193,756
  • 157
  • 432
  • 708
stefan.schwetschke
  • 8,862
  • 1
  • 26
  • 30
  • It can't be compiled: `missing arguments for method from in trait FromSignatures; follow this method with _ if you want to treat it as a partially applied function` – Freewind Jun 18 '13 at 10:16
  • 1
    You would query the `Queryable` the same as a `Table`, so the syntax above looks more illustrative. The compilable code would probably look like: `from(list)(l => compute(count))` – jcern Jun 18 '13 at 11:58
0

In such cases it might make sense to make a common query builder, so you can keep the condition logic at a single place. It's handy when you are paging a query result set.

def queryBuilder[T](action: User => WhereState[Conditioned] => QueryYield[T]) : Query[T] = from(users)(u => action(u)(where(u.age>20)))

def countQuery = queryBuilder(u => w => w.compute(count))

def selectQuery = queryBuilder(u => w => w.select(u))
agabor
  • 662
  • 6
  • 7
0

Here is an example of DAO object:

def countByJobPostingId(jobPostingId: Int): Long = {
  inTransaction {
    val q = from(table)(t =>
      where(t.jobPostingId === jobPostingId)
        compute count
    )

    LOG.debug(q.statement)

    q.head.measures
  }
}