factor out database query code