fixing memory leak from not properly closing queries