implemented query rewrite