Refactor some code to move the DB stuff somewhere else