How to safely cancel a database query