Magento development note 5. In any fast iteration project, it is a headache to ensure the synchronization of development and production (current network) databases. Magento provides a system for creating resource migration versions. in any fast iteration project, it is a headache to ensure the synchronization of development and production (current network) databases. Magento provides a system for creating resource migration versions, which can help us deal with this problem that is constantly encountered during the development process. Www.2cto.com
We created the weblogpost model last time. This time, we execute create table directly. We will not create a Setup Resource for our module, and this Resource will create a table. We will also create an upgrade script to upgrade the installed module. In general
1. add SetupResource in config
2. create a resourceclass file
3. create installerscript
4. create an upgrade script
Add Setup Resource
In Add the following
XStarX_Weblog XStarX_Weblog_Model_Resource_Mysql4_Setup
Core_setup
A tag is used to uniquely represent SetupResource. Modelname_setup is generally encouraged. XStarX_WeblogThe label should contain the Pachagename_Modulename of our module. Last XStarX_Weblog_Model_Resource_Mysql4_Setup It should contain the name of the Setup Resource class we want to create. For basic scripts, there is no need to create your own classes, but this can be more flexible in the future.
After adding the configuration, clear the cache and load the Magento Site. you will find an exception.
Fatalerror: Class 'xstarx _ Weblog_Model_Resource_Mysql4_Setup 'not found in
Magento tries to instantiate the class we declared in config, but it cannot be found. We need to create such a class file app/code/local/XStarX/Weblog/Model/Resource/Mysql4/Setup. php
ClassXStarX_Weblog_Model_Resource_Mysql4_Setup extendsMage_Core_Model_Resource_Setup {}
Now reload the Magento website, and the exception disappears.
Create installation script
Next, we will create an installation script. The script contains the previous CREATETABLE statement.
First, let's take a look at config. xml.
0.1.0
This part is necessary in the configuration file, indicating the module and also telling the version. The installation script must be based on the version. Create a file in the following locations
App/code/local/XStarX/Weblog/SQL/weblog_setup/mysql4-install-0.1.0.php
Echo 'running This Upgrade: '. get_class ($ this). "\ n
\ N ";
Die ("Exit for now ");
The weblog_setup part of the path matches the config. xml file. . The 0.1.0 part matches the module version. Clear the cache and load the page. you can see
Running This Upgrade: Alanstormdotcom_Weblog_Model_Resource_Mysql4_Setup Exit for now...
This means that the update script is executed. In the end, we put the SQL update file here, but now we focus on the setup mechanism. Remove the die statement,
Echo 'running This Upgrade: '. get_class ($ this). "\ n
\ N ";
Reload the page and you can see that the upgrade message is displayed in the first part of the page. Reload, the page will return to normal. Because setup is the same. It is impossible to always set up.
Create installation script
MagenoSetup Resources allows us to simply place the installation script and upgrade script, and then the system will automatically execute. This allows the data migration script in our system to be retained once.
Use the database client to view core_resroucetable
Mysql> select * from core_resource;
+ ----------------------- + --------- + | Code | version | + ----------------------- + ----- +
| Adminnotification_setup | 1.0.0 |
| Admin_setup | 0.7.1 |
| Amazonpayments_setup | 0.1.2 |
| Api_setup | 0.8.1 |
| Backup_setup | 0.7.0 |
| Bundle_setup | 0.1.7 |
| Catalogindex_setup | 0.7.10 |
| Cataloginventory_setup | 0.7.5 |
| Catalogrule_setup | 0.7.7 |
| Catalogsearch_setup | 0.7.6 |
| Catalog_setup | 0.7.69 |
| Checkout_setup | 0.9.3 |
| Chronopay_setup | 0.1.0 |
| Cms_setup | 0.7.8 |
| Compiler_setup | 0.1.0 |
| Contacts_setup | 0.8.0 |
| Core_setup | 0.8.13 |
| Cron_setup | 0.7.1 |
| Customer_setup | 0.8.11 |
| Cybermut_setup | 0.1.0 |
| Cybersource_setup | 0.7.0 |
| Dataflow_setup | 0.7.4 |
| Directory_setup | 0.8.5 |
| Downloadable_setup | 0.1.14 |
| Eav_setup | 0.7.13 |
| Eway_setup | 0.1.0 |
| Flo2cash_setup | 0.1.1 |
| Giftmessage_setup | 0.7.2 |
| Googleanalytics_setup | 0.1.0 |
| Googlebase_setup | 0.1.1 |
| Googlecheckout_setup | 0.7.3 |
| Googleoptimizer_setup | 0.1.2 |
| Ideal_setup | 0.1.0 |
| Log_setup | 0.7.6 |
| Newsletter_setup | 0.8.0 |
| Oscommerce_setup | 0.8.10 |
| Paybox_setup | 0.1.3 |
| Paygate_setup | 0.7.0 |
| Payment_setup | 0.7.0 |
| Paypaluk_setup | 0.7.0 |
| Paypal_setup | 0.7.2 |
| Poll_setup | 0.7.2 |
| Productalert_setup | 0.7.2 |
| Protx_setup | 0.1.0 |
| Rating_setup | 0.7.2 |
| Reports_setup | 0.7.7 |
| Review_setup | 0.7.4 |
| Salesrule_setup | 0.7.7 |
| Sales_setup | 0.9.38 |
| Sendfriend_setup | 0.7.2 |
| Shipping_setup | 0.7.0 |
| Sitemap_setup | 0.7.2 |
| Strikeiron_setup | 0.9.1 |
| Tag_setup | 0.7.2 |
| Tax_setup | 0.7.8 |
| Usa_setup | 0.7.0 |
| Weblog_setup | 0.1.0 |
| Weee_setup | 0.13 |
| Wishlist_setup | 0.7.4 |
+ ------------------------- + --------- + 59 rowsin set (0.00 sec)
This table contains the list of all installed modules and corresponding versions. At the end of the table, we can see
| Weblog_setup | 0.1.0 |
This is how Magento knows whether to re-execute the script. If both are successful, the page will be loaded. Weblog_setup has been installed, so you do not need to update it. To reinstall the script, you need to delete the rows in the table. We can delete it now
DELETE from core_resource where code = 'weblog _ setup ';
Then, delete the corresponding table.
Drop table blog_posts;
Add
$ Installer = $ this;
$ Installer-> startSetup ();
$ Installer-> run ("
Create table '{
$ Installer-> getTable ('weblog/blogpost ')}'(
'Blogpost _ id' int (11) not null auto_increment,
'Title' text,
'Post' text,
'Date' datetime default NULL,
'Timestamp' timestamp not null default CURRENT_TIMESTAMP, primary key ('blogpost _ id '))
ENGINE = InnoDBDEFAULT CHARSET = utf8;
INSERTINTO '{$ installer-> getTable ('weblog/blogpost')} 'values (1, 'My newtitle', 'This is a blog post ', '2017-07-01 00:00:00 ', '2017-07-02 23:12:30 ');");
$ Installer-> endSetup ();
Clear the cache and load the page. you can see that blog_posts is created again and there is a data record.
Create installation script --- problem
The above installation may not be so smooth, and an error will be reported in magento1.7
Mage_Eav_Exception: Can't create table: module_entity
How can this problem be solved?
Debug createEntityTables () method, which can be seen at the end
$ Connection-> beginTransaction (); try {foreach ($ tables as $ tableName = >$ table) {$ connection-> createTable ($ table );} $ connection-> commit ();} catch (Exception $ e) {Zend_Debug: dump ($ e-> getMessage (); $ connection-> rollBack (); throw Mage: exception ('mage _ eav', Mage: helper ('eav')->__ ('Can \'t create table: % s ', $ tableName ));}
Check the underlying error: UserError: DDL statements are not allowed in transactions
Then follow up the commit function
/*** Check transaction level in case of DDL query ** @ param string | Zend_Db_Select $ SQL * @ throws Zend_Db_Adapter_Exception */protected function _ checkDdlTransaction ($ SQL) {if (is_string ($ SQL) & $ this-> getTransactionLevel ()> 0) {$ startSql = strtolower (substr (ltrim ($ SQL), 0, 3 )); if (in_array ($ startSql, $ this-> _ ddlRoutines) {trigger_error (Varien_Db_Adapter_Interface: ERROR_DDL_MESSAGE, E_USER_ERROR );}}}
The conclusion is that Mysql does not support DDL Transaction.
Therefore, rewrite the createEntityTable method in app/code/local/{CompanyName}/{ModuleName}/Setup/Helper. php.
{... /*** Remove transaction code due to issues with errors. * // $ connection-> beginTransaction (); try {foreach ($ tables as $ tableName = >$ table) {$ connection-> createTable ($ table );} $ connection-> commit ();} catch (Exception $ e) {// $ connection-> rollBack (); throw Mage: exception ('mage _ eav', Mage:: helper ('eav')->__ ('Can \'t create table: % s', $ tableName ));}}}
Then the problem is solved.
Setup script profiling
Let's explain one line at a time. First
$ Installer = $ this;
Each installation script is executed from the SetResource class (created above ). This means that the $ this reference in the script is a reference to the class instantiation. If it is not necessary, most of the installation scripts in the core system name $ this without installer. this is also the case here.
The following two methods are available:
$ Installer-> startSetup ();
//...
$ Installer-> endSetup ();
If you view the Mage_Core_Model_Resource_Setup class (in the app/code/core/Mage/Core/Resource/Setup. php directory), you can see the following content:
Public function startSetup ()
{
$ This-> _ conn-> multi_query ("
SET SQL _MODE = '';
SET @ OLD_FOREIGN_KEY_CHECKS = @ FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS = 0;
SET @ OLD_ SQL _MODE = @ SQL _MODE, SQL _MODE = 'no _ AUTO_VALUE_ON_ZERO ';");
Return $ this;
}
Public function endSetup ()
{
$ This-> _ conn-> multi_query ("
SET SQL _MODE = IFNULL (@ OLD_ SQL _MODE ,'');
SET FOREIGN_KEY_CHECKS = IFNULL (@ OLD_FOREIGN_KEY_CHECKS, 0 );");
Return $ this;
}
Finally, execute
$ Installer-> run (...);
This accepts an SQL statement that includes creating a database. You can define any query, separated by semicolons. At the same time, pay attention
$ Installer-> getTable ('weblog/blogpost ')
The getTable method allows us to pass in the Magento Model URI and obtain its table name. If not necessary, use the following method for execution. The Mage_Core_Model_Resource_Setup class contains many useful Helper methods. The most effective learning is to study the Magento core installer scripts.
Module upgrade
The above describes how to initialize a data table, but how to change the existing structure of Mo Xiang? Magento's Setup Resources supports a simple version policy that allows us to automatically execute scripts to upgrade our modules.
Once Magento executes an installation script, it will not execute another installation script again. At this time, we should create an upgrade script. The upgrade script is very similar to the installation script, except for some key points.
At the beginning, we create a script in the following locations,
XStarX/Weblog/SQL/weblog_setup/mysql4-upgrade-0.1.0-0.2.0.php
Echo 'testing our upgrade script (mysql4-upgrade-0.1.0-0.2.0.php) and halting execution to avoid updating the system version number
';
Die ();
The upgrade script and installation script are in the same directory, but slightly different. First, the file name must contain upgrade. Second, there must be two versions separated. The first is the source version of the upgrade, and the second is the Target version of the upgrade.
After the cache is cleared, the page is reloaded, but the script is not executed at this time. We need to update the version information in config. xml to trigger the upgrade.
0.2.0
After a new version number is written, if the cache is cleared and the website is loaded, the output is displayed. At this time, there is another key point to be aware of, so do not panic to do this step first. Create another file in the same directory.
XStarX/Weblog/SQL/weblog_setup/mysql4-upgrade-0.1.0-0.1.5.php
Echo 'testing our upgrade script (mysql4-upgrade-0.1.0-0.1.5.php) and NOT halting execution
';
In this case, clear the cache and load the page. you can see two messages. When Magento finds that the version number is changed, it will execute all executable scripts to update the module. Although we have never created Version 0.1.5, Magento will see the upgrade script and then try to execute it. Generally, scripts are executed in ascending order. The following data indicates this
Mysql> select * from core_resource where code = 'weblog _ setup'; + -------------- + --------- +
| Code | version | + -------------- + --------- +
| Weblog_setup | 0.1.5 | + -------------- + --------- +
1 row in set (0.00 sec)
The data table version is 1.5. This is because we upgraded from 1.0 to 1.5, but did not perform the upgrade from 1.0 to 2.0. Now, let's get down to the point. Go back to the script and first modify the upgrade script 0.1.0-0.2.0.
$ Installer = $ this;
$ Installer-> startSetup ();
$ Installer-> run ("
Alter table '{$ installer-> getTable ('weblog/blogpost ')}'
CHANGE post text not null ;");
$ Installer-> endSetup ();
Die ("You'll see why this is here in a second ");
Refresh the page, but nothing happens. Why is the upgrade script not executed?
1. weblog_setup resource is version 0.1.0
2. we want to upgrade the module to 0.2.0.
3. Magento: see the upgrade module. There are two scripts to execute: 0.1.0-0.1.5 and 0.1.0-0.2.0.
4. Magento load the queue and then execute
5. Magento execute scripts 0.1.0 to 0.1.5.
6. Weblog_setup resource is 0.1.5 now
7. Magento execute the script 0.1.0 to 0.2.0, and the execution stops.
8. when loading the next page, Magento saw that weblog_set was in Version 0.1.5, but did not see any script executed starting from 0.1.5 (earlier versions started with 0.1.0)
The correct method is as follows: rename the file
Mysql4-upgrade-0.1.0-0.1.5.php # This goes from 0.1.0 to 0.1.5
Mysql4-upgrade-0.1.5-0.2.0.php # This goes 0.1.5 to 0.2.0
Magento is capable of loading two upgrades at a time. You can clear the core_resource table information to complete the final test.
Update core_resource set version = '0. 1.0 'where code = 'weblog _ setup ';
Magento performs upgrade based on the configuration file. Therefore, you must pay attention to adding scripts during collaborative development.
Synchronizing databases on the current network is a headache. Magento provides a system for creating resource migration versions ,...