When you setup the module at firstime, setup_module table doesn’t have a setup data for your custom module, then the magento system will checks for the setup_version of the module in its module.xml file
<module name="Quadone_Sample" schema_version="0.0.5" setup_version="1.0.0" />
Then it will execute Setup/InstallSchema.php to create installation script.
app/code/Quadone/Sample/Setup/InstallSchema.php
<?php
namespace Quadone\Sample\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class InstallSchema implements InstallSchemaInterface
{
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$connection = $setup->getConnection();
$setup->startSetup();
/**
* Create table ‘quadone_sample'
*/
$table = $connection->newTable(
$setup->getTable('quadone_sample')
)->addColumn(
'qsample_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Quadone Id'
)->addColumn(
'name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
8,
['nullable' => false, 'default' => 'default'],
'Name'
)->addColumn(
'email',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['nullable' => false, 'default' => 'default'],
'Email Id'
);
$connection->createTable($table);
$setup->endSetup();
}
}
Clear the cache and run bin/magento setup:upgrade
Upgrading Schema
Change the setup_version in module.xml
<module name="Quadone_Sample" schema_version="0.0.5" setup_version="2.0.0" />
System will executes the Setup/UpgradeSchema.php
<?php
namespace Quadone\Sample\Setup;
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)
{
$connection = $setup->getConnection();
$setup->startSetup();
if (version_compare($context->getVersion(), '2.0.0', '<')) {
//2nd parameter is the modified setup_version in module.xml
$setup->getConnection()->addColumn(
$setup->getTable(‘quadone_sample’),
'age',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'unsigned' => true,
'nullable' => false,
'default' => '0',
'comment' => 'Age'
]
);
}
$setup->endSetup();
}
}