refactoring the sql side into reasonable sized chunks