Porting sql queries appropriately