Refactor database implementation