finalize query function