Improvements to database error handling, fixed infinite loop in fixing tables code