Yii spiritual path (1) @ Migration data Migration
Data Migration refers to the migration of database tables created by the team to synchronize information between teams and unify data.
Database Migration
General steps:
1. in The migrate of yii2, it is usually used to modify the database data table, mainly to operate on the structure and a small part of the data (rarely encounter big data, if the data volume is large, use direct export and import of data tables ).
2. generate or modify the database table locally, and run the statement at the backend:./yii migrate/create
3. after the backend executes the migrate command, a migrate script is generated. this script is mainly used to store SQL statements and will be uploaded as the code is released for other members to synchronize the database, implement real data migration.
4. when other members pull the latest code back to the local machine, execute./yii migrate to update the data migration status and synchronize the latest data migration to the local machine.
Concept
When developing and maintaining a database-driven application, the database structure changes with the code.
For example, during application development, a new table is added and must be added. after the application is deployed to the production environment, an index is required to improve the query performance. Because the source code often needs to be changed when the structure of a database changes, Yii provides a database migration function that records database changes, so that the database and source code are controlled by the version.
The following steps show how the database migration tool is used by the development team:
-
Tim creates a new migration object (for example, creating a new form and changing the field definition ).
-
Tim submits the new migration object to the code management system (such as Git and Mercurial ).
-
Doug updated the version from the code management system and obtained the new migration object.
-
Doug submitted the migration object to the local development Database. in this way, Doug synchronized the modifications made by Tim.
The following steps show us how to release a new version with database migration to the production environment:
-
Scott creates a release tag for a project version that contains database migration.
-
Scott updates the source code of the release tag to the server in the production environment.
-
Scott submits all incremental database migration to the production environment database.
Yii provides a complete set of migration command line tools, through which you can:
All of these tools can be operated through the yii migrate command. Note: migration not only applies to database tables, but also adjusts existing data to adapt to new forms, create RBAC layers, or clear caches.
Create migration
Run the following command to create a new migration:
yii migrate/create
The name parameter is a brief description of the new migration.
For example, if this migration is used to create a form called news, you can use the name create_news_table and run the following command:
yii migrate/create create_news_table
Note: Because the name parameter is used to generate a part of the migration class name, it should only contain letters, numbers, and underscores.
The above Command will create a new PHP class file named m150101_185401_create_news_table.php under the @ app/migrations directory.
This file contains the following code, which is used to declare a migration class m150101_185401_create_news_table with the code framework attached:
Each database migration is defined as a PHP class inherited from yiidbMigration. The class name follows the m
_
Is automatically generated.
In the migration class, you should write the code to change the database structure in the up () method. You may also need to write code in the down () method to restore the changes made by the up () method.
When you upgrade the database through migration, the up () method will be called. otherwise, down () will be called. The following code creates a news table using the migration class:
use yii\db\Schema; use yii\db\Migration; class m150101_185401_create_news_table extends \yii\db\Migration{ public function up() { $this->createTable('news', [ 'id' => Schema::TYPE_PK, 'title' => Schema::TYPE_STRING . ' NOT NULL', 'content' => Schema::TYPE_TEXT, ]); } public function down() { $this->dropTable('news'); } }
Note: not all migrations are recoverable.
For example, if the up () method deletes a row of data in the table, the data cannot be restored using the down () method. Sometimes, you may just be too lazy to execute the down () method, because it is not so common in restoring database migration. In this case, you should return false in the down () method to indicate that the migration cannot be restored.
Submit for migration
To upgrade the database to the latest structure, you should use the following command to submit all new migrations:
yii migrate
This command will list all uncommitted migrations so far.
If you are sure that you need to submit the migration, it will run up () in each new migration class one by one according to the timestamp sequence in the class name () or the safeUp () method. If any of the migration submission fails, this command will exit and stop the rest of the unexecuted migration tasks.
For each successfully submitted migration, this command inserts a record containing the migration successfully submitted by the application in a database table called migration. this record will help the migration tool determine which migration has been submitted, which have not been submitted yet.
Tip: the migration tool will automatically create a migration table in the database, which is specified in the yiiconsolecontrollersMigrateController: db option of the command. By default, it is specified by db application component.
Sometimes, you only need to submit one or a few migration jobs. you can use this command to specify the number of items to be executed, rather than executing all the available migration jobs. For example, the following command will try to submit the first three available migrations:
yii migrate 3
You can also specify a specific migration. use the migrate/to command in the following format to specify which migration should the database submit:
Yii migrate/to 150101_185401 # using timestamp to specify the migration use timestamps to specify the migration yii migrate/to "18:54:01" # using a string that can be parsed by strtotime () use a string yii migrate/to m15010108185401_create_news_table # using full name that can be parsed by strtotime () to use the full name yii migrate/to 1392853618 # using UNIX timestamp
If there are still uncommitted migration before the specified migration to be submitted, the uncommitted migration will be submitted first before the specified migration is executed.
If the specified submitted migration has been submitted before, the subsequent migration will be restored.
Restore migration
You can use the following command to restore the migration submitted for one or more of the comments:
Yii migrate/down # revert the most recently applied migration restore the most recent submitted migration yii migrate/down 3 # revert the most 3 recently applied migrations restore the most recent three submitted migration
Note: not all migrations can be restored. Attempts to restore this type of migration may result in an error or even termination of all restoration processes.
Redo migration
Redo migration means to restore the specified migration and then submit it again. As follows:
Yii migrate/redo # redo the last applied migration redo the latest submitted migration yii migrate/redo 3 # redo the last 3 applied migrations redo the latest three submitted migration
Note: If a migration cannot be restored, you cannot redo it.
List migration
You can use the following command to list the submitted or unsubmitted migration tasks:
Yii migrate/history # displays the migration yii migrate/history 5 submitted in the last 10 times # displays the migration yii migrate/history all submitted in the last 5 times # displays all submitted migration yii migrate /new # show the first 10 unsubmitted migration yii migrate/new 5 # show the first five unsubmitted migration yii migrate/new all # show all unsubmitted migration
Modify migration history
Sometimes you may need to simply mark that your database has been upgraded to a specific migration, rather than submitting or restoring the migration. This often happens when you manually change a specific state of the database, and you do not want the corresponding migration to be submitted repeatedly. You can use the following command to achieve the goal:
Yii migrate/mark 150101_185401 # use a time stamp to specify the migration yii migrate/mark "18:54:01" # Use a strtotime () parsed string yii migrate/mark m15010109185401_create_news_table # use full name yii migrate/mark 1392853618 # use UNIX timestamp
This command will add or delete several rows of data in the migration table to indicate that the database has been submitted to a specified migration.
No migration will be submitted or restored during the execution of this command.
Global configuration command
It is annoying to enter the same parameters repeatedly when running the migration command. at this time, you can configure the global settings in the application configuration. once and for all:
return [ 'controllerMap' => [ 'migrate' => [ 'class' => 'yii\console\controllers\MigrateController', 'migrationTable' => 'backend_migration', ], ],];
As shown in the preceding configuration, the backend_migration table is used to record the migration history every time the migration command is run. You no longer need to specify this history table using the migrationTable command line parameter.
Migrate multiple databases
By default, the migration will be submitted to the same database defined by db application component. If you need to submit data to different databases, you can specify the database command line option as follows,
yii migrate --db=db2
The above Command will submit the migration to the db2 database.
Occasionally, you need to submit some data for migration to one database, while others need to submit data to another database. To achieve this, you should specify the ID of the required database component when implementing a migration class, as shown below:
use yii\db\Schema;use yii\db\Migration;class m150101_185401_create_news_table extends Migration{ public function init() { $this->db = 'db2'; parent::init(); }}
Even if you use the database command line option to specify another different database, the above migration will still be submitted to db2. Note that the historical migration information will still be recorded in the database specified by the db command line option.
If multiple migrations use the same database, we recommend that you create a base class for migration that contains the above init () code. Then, each migration class inherits the base class.
Tip: in addition to setting the yiidbMigration: db parameter, you can create a new database connection in the migration class to operate different databases. Then, use the DAO method to operate different databases through these connections.
Another policy that allows you to migrate multiple databases is to store the migration to different directories. then, you can run the following commands to migrate different databases:
yii migrate --migrationPath=@app/migrations/db1 --db=db1yii migrate --migrationPath=@app/migrations/db2 --db=db2...
The first command submits the migration under the @ app/migrations/db1 directory to the db1 database, the second command submits the migration under @ app/migrations/db2 to the db2 database, and so on.