
この記事では、Magento 2のモジュール用のSQLスクリプトをインストールおよびアップグレードする方法について説明します。 モジュールをインストールまたはアップグレードする際に、データベース構造を変更したり、現在のテーブルに新しいデータを追加したりする必要がある場合があります。これを行うために、Magento 2ではいくつかのクラスが提供されており、それらすべてを行うことができます。
クラスはすべてapp/code/Vendor/Module/Setupフォルダに配置されます。以下のコマンドラインを実行すると、モジュールのインストール/アップグレードスクリプトが実行されます。
php bin/magento setup:upgrade
目次
1. インストールスクリプト: Install Schema & Install Data
InstallSchema クラスと InstallData クラスは、モジュールのインストール時に実行されます。
Magento 2 の InstallSchema セットアップスクリプトは、データベーススキーマの変更 (データベーステーブルの作成または変更) に使用されます。これは、SmartOsc_helloworld_postテーブルを作成するためのセットアップスクリプトです。
ファイル: app/code/SmartOsc/HelloWorld/Setup/InstallSchema.php
<?php
namespace SmartOsc\HelloWorld\Setup;
class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface
{
public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
if (!$installer->tableExists('SmartOsc_helloworld_post')) {
$table = $installer->getConnection()->newTable(
$installer->getTable('SmartOsc_helloworld_post')
)
->addColumn(
'post_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[
'identity' => true,
'nullable' => false,
'primary' => true,
'unsigned' => true,
],
'Post ID'
)
->addColumn(
'name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable => false'],
'Post Name'
)
->addColumn(
'url_key',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Post URL Key'
)
->addColumn(
'post_content',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Post Post Content'
)
->addColumn(
'tags',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Post Tags'
)
->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
1,
[],
'Post Status'
)
->addColumn(
'featured_image',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Post Featured Image'
)
->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
'Updated At')
->setComment('Post Table');
$installer->getConnection()->createTable($table);
$installer->getConnection()->addIndex(
$installer->getTable('SmartOsc_helloworld_post'),
$setup->getIdxName(
$installer->getTable('SmartOsc_helloworld_post'),
['name', 'url_key', 'post_content', 'tags', 'featured_image'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
),
['name', 'url_key', 'post_content', 'tags', 'featured_image'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
);
}
$installer->endSetup();
}
}
このファイルを見ると、次のことがわかります。
クラスは、SchemaSetupInterfaceとModuleContextInterfaceを継承しています。
このクラスは、SchemaSetupInterface と ModuleContextInterface の 2 つの引数を持つ install() メソッドを持っています。SchemaSetupInterface は、データベースサーバーと対話するための多くの機能を提供するセットアップオブジェクトです。ModuleContextInterface には、1つのメソッド getVersion() があり、モジュールの現在のバージョンを返します。
上の例では、SmartOsc_helloworld_post という名前のテーブルを作成し、post_id, name, post_content, created_at …. というカラムを設定しています。
InstallData は InstallSchema クラスの後に実行され、データベースのテーブルにデータを追加します。
ファイル:app/code/SmartOsc/HelloWorld/Setup/InstallData.php
<?php
namespace SmartOsc\HelloWorld\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
protected $_postFactory;
public function __construct(\SmartOsc\HelloWorld\Model\PostFactory $postFactory)
{
$this->_postFactory = $postFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$data = [
'name' => "How to Create SQL Setup Script in Magento 2",
'post_content' => "In this article, we will find out how to install and upgrade sql script for module in Magento 2. When you install or upgrade a module, you may need to change the database structure or add some new data for current table. To do this, Magento 2 provide you some classes which you can do all of them.",
'url_key' => '/magento-2-module-development/magento-2-how-to-create-sql-setup-script.html',
'tags' => 'magento 2,SmartOsc helloworld',
'status' => 1
];
$post = $this->_postFactory->create();
$post->addData($data)->save();
}
}
このクラスは、InstallSchemaと同じ概念を持ちます。
2. アップグレードスクリプト:UpgradeSchema & UpgradeData
このファイルは、モジュールがインストールまたはアップグレードされたときに実行されます。このクラスは、モジュールがアップグレードされるたびに実行されるので、Installクラスとは異なります。そこで、app/code/SmartOsc/HelloWorld/etc/にあるmodule.xmlのsetup_versionという属性を確認し、バージョンごとにスクリプトを分ける必要があります。
この例では、attrubute setup_versionを1.2.0に変更します。
ファイル:app/code/SmartOsc/HelloWorld/etc/module.xml
内容は次のようになります:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="SmartOsc_HelloWorld" setup_version="1.2.0">
</module>
</config>
アップグレード方式:
ファイル:app/code/SmartOsc/HelloWorld/Setup/UpgradeSchema.php
<?php
namespace SmartOsc\HelloWorld\Setup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
class UpgradeSchema implements UpgradeSchemaInterface
{
public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
$installer = $setup;
$installer->startSetup();
if(version_compare($context->getVersion(), '1.2.0', '<')) {
$installer->getConnection()->addColumn(
$installer->getTable( 'SmartOsc_helloworld_post' ),
'test',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'nullable' => true,
'length' => '12,4',
'comment' => 'test',
'after' => 'status'
]
);
}
$installer->endSetup();
}
}
このクラスでは、モジュールがアップグレードされるたびに実行されるupgrade()メソッドを使用します。また、各バージョンのスクリプトを追加するために、バージョンを比較しなければなりません。
アップグレードデータ
これは UpgradeSchema クラスと同じです。
ファイル:app/code/SmartOsc/HelloWorld/Setup/UpgradeData.php
<?php
namespace SmartOsc\HelloWorld\Setup;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
class UpgradeData implements UpgradeDataInterface
{
protected $_postFactory;
public function __construct(\SmartOsc\HelloWorld\Model\PostFactory $postFactory)
{
$this->_postFactory = $postFactory;
}
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
if (version_compare($context->getVersion(), '1.2.0', '<')) {
$data = [
'name' => "Magento 2 Events",
'post_content' => "This article will talk about Events List in Magento 2. As you know, Magento 2 is using the events driven architecture which will help too much to extend the Magento functionality. We can understand this event as a kind of flag that rises when a specific situation happens. We will use an example module SmartOsc_HelloWorld to exercise this lesson.",
'url_key' => '/magento-2-module-development/magento-2-events.html',
'tags' => 'magento 2,SmartOsc helloworld',
'status' => 1
];
$post = $this->_postFactory->create();
$post->addData($data)->save();
}
}
}
3. 定期的なスクリプト
recurring script は、モジュールセットアップスクリプトの後に、コマンドライン php bin/magento setup:upgrade が実行されるたびに実行されるスクリプトです。
このスクリプトは InstallSchema クラスと同じように定義されますが、クラスの名前が異なります。このクラスの例は、 vendor/magento/module-indexer/Setup/Recurring.php にあります。
4. アンインストール・スクリプト
Magento 2では、モジュールをアンインストールすることで、まだインストールされていないテーブルやデータをすべて削除することができます。このクラスの例を以下に示します。
ファイル: app/code/SmartOsc/HelloWorld/Setup/Uninstall.php
<?php
namespace SmartOsc\HelloWorld\Setup;
use Magento\Framework\Setup\UninstallInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
class Uninstall implements UninstallInterface
{
public function uninstall(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
$installer->getConnection()->dropTable($installer->getTable('SmartOsc_helloworld_post'));
$installer->endSetup();
}
}