refactored database logic