Refactoring SQL stuff, removing old/unused code