Refactored Database code