Clean up the logic in install_insert_db

Check the things in an order that makes sense and minimise duplication.