The way of the practice of Yii (i) @Migration data migration

Source: Internet
Author: User

Briefly

Data migration is the database table in the team to build the migration operations, to achieve the team to synchronize information between each other, data unification.

Database migration

General steps:

1, in the yii2 of the migrate, is usually used to modify the database data table operation, mainly on the structure and a small number of data operations (rarely encounter big data, if the face of large data volume, using Data table Direct Export import).

2. Generate or modify a database table locally, and the back end executes the statement:./yii migrate/create

3, after the execution of the migrate instruction will generate a migrate script, the script is mainly used to store SQL statements, but also with the release of the code to upload, for other members to synchronize the database, to achieve true data migration.

4, other members pull the latest code back to local, execute./YII migrate update the Data migration status to synchronize the latest data migration to local.

Concept

When developing and maintaining a database-driven application, the structure of the database changes as the code changes.

For example, in the process of developing an application, a new table is added and must be added; After the application is deployed to the production environment, an index needs to be established to improve the performance of the query, and so on. Because the source code also often needs to change when a database structure changes, YII provides a database migration feature that records changes to the database so that the database and source code are versioned together.

The next steps show us how the database migration Tool is used by the development team:

    1. Tim creates a new migration object (for example, creating a new form, changing the definition of a field, and so on).

    2. Tim submits this new migration object to the Code management system (for example, git,mercurial).

    3. Doug updates the version from the code management system and gets to this new migration object.

    4. Doug submits the migrated object to the local development database, so Doug synchronizes the changes made by Tim.

The next steps show us how to publish a new version of the database migration that comes with the production environment:

    1. Scott creates a publishing label for a project version that contains a database migration.

    2. Scott updates the source code for the release tag to the server on the production environment.

    3. Scott commits all incremental database migrations to the production environment database.

YII provides a complete set of migration command-line tools through which you can:

    • Create a new migration (./yii migrate/create Migration description);

    • Submit the migration;

    • Resume migration;

    • Re-submit the migration;

    • Reality migration history and status.

All of these tools can be manipulated using the Yii migrate command. Note: Migration is not just for database tables, it also adjusts existing data to accommodate new forms, create RBAC hierarchies, or clear caches.

Create a migration

Use the following command to create a new migration:

Yii migrate/create 
 
  

Required parameter name is a brief description of the new migration.

For example, if this migration is used to create a form called news, then 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 portion of the migrated class name, the parameter should contain only letters, numbers, and underscores.

The above command will create a new PHP class file named m150101_185401_create_news_table.php in the @app/migrations directory.

The file contains the following code, which declares a migration class m150101_185401_create_news_table with a code framework:

     

Each database migration will be defined as a PHP class that inherits from Yiidbmigration. The name of the class is automatically generated in the format M _, where

    • Refers to the UTC time when the Create migration command was executed.

    • The name parameter value is the same as when you execute the command.

In the migration class, you should write code that alters the structure of the database in the Up () method. You may also need to write code in the Down () method to recover the changes made by the up () method.

When you upgrade the database through migration, the up () method will be called and, conversely, down () will be called. The following code shows how to create a news table by migrating a 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 from a table, this data cannot be recovered by the down () method. Sometimes, you may just be lazy to execute the down () method, because it is not so common in recovering a database migration. In this case, you should return false in the down () method to indicate that the migration is unrecoverable.

Submit Migration

In order to upgrade the database to the latest structure, you should use the following command to submit all new migrations:

Yii Migrate

This command lists any uncommitted migrations to date.

If you are sure that you need to commit these migrations, it will follow the sequence of timestamps in the class name, one after the other to run the up () or Safeup () method inside each new migration class. If any of the migration commits fail, then this command exits and stops the remaining migrations that have not yet been performed.

For each successful commit migration, this command inserts a record containing the application's successful commit migration in a database table called migration, which will help the migration tool determine which migrations have been committed and which have not yet been committed.

Tip: The migration tool will automatically create a migration table in the database that is specified in the command's Yiiconsolecontrollersmigratecontroller::d b option. By default, the DB application component is specified.

Sometimes you may only need to commit one or a few migrations, and you can use this command to specify the number of bars that need to be executed instead of performing all the available migrations. For example, the following command will attempt to commit the first three available migrations:

Yii Migrate 3

You can also specify a specific migration by using the Migrate/to command in the following format to specify which migration the database should commit:

Yii migrate/to 150101_185401 # using timestamp to specify the migration uses timestamps to specify the migration yii migrate/to "2015-01-01 18:54:01" # Using a string, the can is parsed by Strtotime () uses an strtotime () to parse the strings of Yii migrate/to m150101_185401_create_news_tabl e # using the full name uses a Unix timestamp for migrate/to 1392853618 # using UNIX timestamp

If there are uncommitted migrations before the migration that you specify to commit, these uncommitted migrations are committed before the specified migration is performed.

If the migrated that was specified has been previously committed, then those migrations after it will be restored.

Restore migration

You can use the following command to restore a migration where one or more of the comments have been submitted:

Yii Migrate/down # Revert the most recently applied migration restore the most recently committed migration Yii Migrate/down 3 # Revert the most 3 recently Applied Migrations Restore the last three committed migrations

Note: Not all migrations can be restored. Attempting to restore this type of migration can result in an error or even a termination of all restore processes.

Redo Migration

The redo migration means that the specified migration is restored first and then submitted again. As shown below:

Yii Migrate/redo # Redo the last applied migration redo the most recent commit of the migration Yii Migrate/redo 3 # Redo 3 applied Migrations Redo Most Migration of nearly three commits

Note: If a migration cannot be restored, then you will not be able to redo it.

List migration

You can use the following commands to list the migrated or uncommitted migrations:

Yii Migrate/history # shows the last 10 commits of the migration Yii migrate/history 5 # shows the last 5 commits of the migrated Yii migrate/history All # shows all the migrated Yii migrate/that have been submitted New # shows the top 10 uncommitted migration Yii migrate/new 5 # shows the first 5 uncommitted migrations of Yii migrate/new All # Show All uncommitted migrations

Modify the migration history

Sometimes you may need to simply mark your database to be upgraded to a specific migration instead of actually committing or restoring the migration. This often happens when you manually change a specific state of the database without having to repeat the migration. Then you can use the following command to achieve your goal:

Yii Migrate/mark 150101_185401 # Use a timestamp to specify the migration yii migrate/mark "2015-01-01 18:54:01" # Use a string that can be parsed by strtotime () Yii Migrat E/mark m150101_185401_create_news_table # using full name Yii migrate/mark 1392853618 # using UNIX timestamps

This command adds or removes a few rows of data from the migration table to indicate that the database has been committed to a specified migration.

No migration will be committed or restored during the execution of this command.

Global configuration commands

It is annoying to have to enter some of the same parameters every time you run the migration command, and then you can choose to configure the configuration globally in the application configuration once and for all:

return [' controllermap ' + = [' migrate ' and ' = '            class ' = ' yii\console\controllers\ Migratecontroller ',            ' migrationtable ' = ' backend_migration ',        ],]    ,;

As shown above, the Backend_migration table will be used to record the migration history each time the migration command is run. You no longer need to specify this history table by migrationtable command line arguments.

Migrating multiple databases

By default, the migration will be committed to the same database as defined by DB application component. If you need to commit to a different database, you can specify the DB command line option as follows,

Yii Migrate--DB=DB2

The above command will commit the migration to the DB2 database.

Occasionally there are times when you need to commit some migration to a database, while others commit to another database. To achieve this, you should specify the ID of the database component you want to use when implementing a migration class, as follows:

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 specify a different database using the DB command-line option, the migration is still committed to DB2. It is important to note that this time the migrated historical information is still recorded in the database specified by the DB command line option.

If you have multiple migrations that use the same database, it is recommended that you create a migrated base class that contains the init () code described above. Then each migration class inherits the base class.

Tip: In addition to setting in the yiidbmigration::d b parameter, you can also manipulate different databases by creating a new database connection in the migration class. These connections are then used to manipulate different databases using the DAO method.

Another strategy that allows you to migrate multiple databases is to store the migration in a different directory, and then you can migrate the different databases by using the following command:

Yii migrate--migrationpath= @app/migrations/db1--db=db1yii migrate--migrationpath= @app/migrations/db2--db=db2 ...

The first command will commit the migration @app the/MIGRATIONS/DB1 directory to the DB1 database, and the second command will commit the migration under the @app/MIGRATIONS/DB2 to the DB2 database, and so on.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.