Rewrite query generation