Further refactoring of the SQL generation code