Improved optimizer SQL, error handling and test cases