Moving queries to db layer