refactor db query