fix query rewriting and add its tests