Magento 2: Setup scripts

Create New Table : 
namespace NameSpace\Module\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)
    {
        $installer = $setup;
        $installer->startSetup();
        
        /*
         * Drop tables if exists
         */
        
        $installer->getConnection()->dropTable($installer->getTable('tbl_name1'));
 
        /*
         *    Create table 'tbl_name1'
         */

 $table = $installer->getConnection()
            ->newTable($installer->getTable('tbl_name1'))
            ->addColumn(
                'entity_id',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                null,
                ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
                'Entity Id'
            )
            ->addColumn(
                'col_name1',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                45,
                ['nullable' => true, 'default' => null],
                'col_name1 collumn comment'
            )
            ->addColumn(
                'col_name2',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                null,
                ['unsigned' => true, 'nullable' => false, 'default' => '0'],
                'col_name2 collumn comment'
            )
            ->addColumn(
                'col_name3_date_time',
                \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                null,
                [],
                'col_name3_date_time collumn comment'
            )
             // Add Indexing in column
             ->addIndex(
                $installer->getIdxName('table_name', ['col_name2']),
                ['col_name2']
            ) 
             // Add Foreign Key
             ->addForeignKey(
                $installer->getFkName(
                        'table1',
                        'Same table collumn name',
                        'othertable',
                        'Other table collumn name'
                ),
                'Same table collumn name',
                $installer->getTable('othertable'),
                'Other table collumn name',
                 \Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
            )
            ->setComment('Table Comments');
          $installer->getConnection()->createTable($table);

        $installer->endSetup();
    }
}


Insert Data In Table :
namespace NameSpace\ModuleName\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{

    /**
     * {@inheritdoc}
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        
        $installer = $setup;

        $installer->startSetup();

        $data = [
            [
                'column_name1' => 'test',
                'column_name2' => 1,
                
            ],
            [
                'column_name1' => 'test',
                'column_name2' => 2,
                
            ],
            
        ];
        foreach ($data as $row) {
            $setup->getConnection()->insertForce($setup->getTable('tableName'), $row);
        }
         $setup->endSetup();
    }
}

Upgrade Schema :
namespace NameSpace\ModuleName\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * @codeCoverageIgnore
 */
class UpgradeSchema implements UpgradeSchemaInterface
{
    /**
     * {@inheritdoc}
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        if (version_compare($context->getVersion(), '0.2.0', '<')) {

            $tableName = $setup->getTable('tableName');
            $setup->getConnection()->addColumn($tableName, 'comment', [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                'length'    => 255,
                'unsigned' => true,
                'nullable' => false,
                'default' => '0',
                'comment' => 'Comment'
            ]);
        }
        $setup->endSetup();
    }
}
Add EAV Attribute : 
namespace NameSpace\ModuleName\Setup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Catalog\Model\Category;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;

class InstallData implements InstallDataInterface
{

    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {

        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        
        $eavSetup->addAttribute(
                Category::ENTITY, 'sale_start_date', [
            'type' => 'datetime',
            'label' => 'Sale start date',
            'input' => 'datetime',
            'visible' => true,
            'default' => '',
            'required' => false,
            'sort_order' => 115,
            'global' => ScopedAttributeInterface::SCOPE_STORE,
            'group' => 'General Information',
                ]
        );

        
    }

}

Comments