Optimization in KDE-PIM
Speed up statistics queries from O(n^2) behavior by avoiding a double inner join.
On Postgres 9.1 the query that uses two inner joins to limit the results
to collections with items with certain flags (like SEEN) is extremely
inefficient, for as yet unknown reasons. To work around this, we filter
manually by leveraging an in-memory cache of flag names to ids and using
those ids to filter.
Approved by vkrause.