Fix bugs with sql generation