The UpgradeSchema script is used when we wish to create new tables or add columns to existing tables. Given that it is run on every setup:upgrade, where setup_module.schema_version is lower than setup_version under <VendorName>/<ModuleName>/etc/module.xml, we are in charge of controlling the code for a specific version. This is usually done via the if-ed version_compare approach.
To better demonstrate this, let's create the <MAGELICIOUS_DIR>/Core/Setup/UpgradeSchema.php file with the following content:
use \Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class UpgradeSchema implements UpgradeSchemaInterface {
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context) {
$setup->startSetup();
if (version_compare($context->getVersion(), '2.0.2') < 0) {
$this->upgradeToVersionTwoZeroTwo($setup);
}
$setup->endSetup();
}
private function upgradeToVersionTwoZeroTwo(SchemaSetupInterface $setup) {
echo 'UpgradeSchema->upgradeToVersionTwoZeroTwo()' . PHP_EOL;
}
}
The if-ed version_compare here reads as follows: if the current module version is equal to 2.0.2, then execute the upgradeToVersionTwoZeroTwo method. If we were to release an updated version of our module, we would need to properly bump up the setup_version of <VendorName>/<ModuleName>/etc/module.xml, or else UpgradeSchema does not make a lot of sense. Likewise, we should always be sure to target a specific module version, thus avoiding code that executes on every version change.
When it comes to UpgradeSchema scripts, the following methods of a database adapter instance, alongside the previously mentioned one, will be of interest:
- dropColumn: Drops the column from a table
- dropForeignKey: Drops the foreign key from a table
- dropIndex: Drops the index from a table
- dropTable: Drops the table from a database
- modifyColumn: Modifies the column definition