Refactored database functions, removed duplication