fix rid in query and reformat code