Major refactoring of generation of SQL