Feature request from mttjohnson, posted on GitHub Nov 06, 2015
Working from the Magento 2.0.0-RC
I ran into a scenario where an setup install script failed halfway through installing some data and I found that it inserted and modified the database to the point it hit an exception. I haven't noticed much use of database transactions inside the install scripts, but I found that it doesn't take much to add them to the start and end of the install() method.
I found an example of using database transactions in \Magento\Checkout\Setup\InstallData and I went ahead and tested wrapping the contents of my install script. It seems like wrapping database install scripts inside a database transaction should be a recommended practice so that we can avoid half installed modules that can be very difficult to troubleshoot afterwards.
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$connection = $setup->getConnection();
try {
$connection->beginTransaction();
// Do a bunch of stuff here that may change things in the database and
// you want to retain the option to rollback the changes if an error occurs
// If no errors occur commit all the database changes
$connection->commit();
} catch (\Exception $e) {
// If an error occured rollback the database changes as if they never happened
$connection->rollback();
throw $e;
}
}
I have run into several situations trying to clean up magento sites that had things half installed and contained additional or missing changes to the database. Having gone through the mess of cleaning up partial upgrades leads me to believe there is room for improvement around the setup scripts.
When would it be an ok idea to partially install data in the database?