Improve Query prepare and add tests.

Change-Id: I2874b0cca2ad4cb5f89785572259113f548c1e8c