adapt for PostgreSQL, and clean up db code a bit

biggest problem was with PostreSQL behaviour on GROUP BY differing
from SQLite (as in http://stackoverflow.com/questions/18038632/).
changed how i'm constructing queries a bit and it's working now.