Class yii\db\Migration

Inheritanceyii\db\Migration » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable, yii\db\MigrationInterface
Uses Traitsyii\db\SchemaBuilderTrait
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/db/Migration.php

Migration is the base class for representing a database migration.

Migration is designed to be used together with the "yii migrate" command.

Each child class of Migration represents an individual database migration which is identified by the child class name.

Within each migration, the up() method should be overridden to contain the logic for "upgrading" the database; while the down() method for the "downgrading" logic. The "yii migrate" command manages all available migrations in an application.

If the database supports transactions, you may also override safeUp() and safeDown() so that if anything wrong happens during the upgrading or downgrading, the whole migration can be reverted in a whole.

Note that some DB queries in some DBMS cannot be put into a transaction. For some examples, please refer to implicit commit. If this is the case, you should still implement up() and down(), instead.

Migration provides a set of convenient methods for manipulating database data and schema. For example, the insert() method can be used to easily insert a row of data into a database table; the createTable() method can be used to create a database table. Compared with the same methods in yii\db\Command, these methods will display extra information showing the method parameters and execution time, which may be useful when applying migrations.

For more details and usage information on Migration, see the guide article on Migration.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$behaviors yii\base\Behavior[] List of behaviors attached to this component. This property is read-only. yii\base\Component
$compact boolean Indicates whether the console output should be compacted. yii\db\Migration
$db yii\db\Connection|array|string The DB connection object or the application component ID of the DB connection that this migration should work with. yii\db\Migration
$maxSqlOutputLength integer Max number of characters of the SQL outputted. yii\db\Migration

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
addColumn() Builds and executes a SQL statement for adding a new DB column. yii\db\Migration
addCommentOnColumn() Builds and execute a SQL statement for adding comment to column. yii\db\Migration
addCommentOnTable() Builds a SQL statement for adding comment to table. yii\db\Migration
addForeignKey() Builds a SQL statement for adding a foreign key constraint to an existing table. yii\db\Migration
addPrimaryKey() Builds and executes a SQL statement for creating a primary key. yii\db\Migration
alterColumn() Builds and executes a SQL statement for changing the definition of a column. yii\db\Migration
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
batchInsert() Creates and executes a batch INSERT SQL statement. yii\db\Migration
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
bigInteger() Creates a bigint column. yii\db\SchemaBuilderTrait
bigPrimaryKey() Creates a big primary key column. yii\db\SchemaBuilderTrait
binary() Creates a binary column. yii\db\SchemaBuilderTrait
boolean() Creates a boolean column. yii\db\SchemaBuilderTrait
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
char() Creates a char column. yii\db\SchemaBuilderTrait
className() Returns the fully qualified name of this class. yii\base\BaseObject
createIndex() Builds and executes a SQL statement for creating a new index. yii\db\Migration
createTable() Builds and executes a SQL statement for creating a new DB table. yii\db\Migration
date() Creates a date column. yii\db\SchemaBuilderTrait
dateTime() Creates a datetime column. yii\db\SchemaBuilderTrait
decimal() Creates a decimal column. yii\db\SchemaBuilderTrait
delete() Creates and executes a DELETE SQL statement. yii\db\Migration
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
double() Creates a double column. yii\db\SchemaBuilderTrait
down() This method contains the logic to be executed when removing this migration. yii\db\Migration
dropColumn() Builds and executes a SQL statement for dropping a DB column. yii\db\Migration
dropCommentFromColumn() Builds and execute a SQL statement for dropping comment from column. yii\db\Migration
dropCommentFromTable() Builds a SQL statement for dropping comment from table. yii\db\Migration
dropForeignKey() Builds a SQL statement for dropping a foreign key constraint. yii\db\Migration
dropIndex() Builds and executes a SQL statement for dropping an index. yii\db\Migration
dropPrimaryKey() Builds and executes a SQL statement for dropping a primary key. yii\db\Migration
dropTable() Builds and executes a SQL statement for dropping a DB table. yii\db\Migration
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
execute() Executes a SQL statement. yii\db\Migration
float() Creates a float column. yii\db\SchemaBuilderTrait
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the migration. yii\db\Migration
insert() Creates and executes an INSERT SQL statement. yii\db\Migration
integer() Creates an integer column. yii\db\SchemaBuilderTrait
json() Creates a JSON column. yii\db\SchemaBuilderTrait
money() Creates a money column. yii\db\SchemaBuilderTrait
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
primaryKey() Creates a primary key column. yii\db\SchemaBuilderTrait
renameColumn() Builds and executes a SQL statement for renaming a column. yii\db\Migration
renameTable() Builds and executes a SQL statement for renaming a DB table. yii\db\Migration
safeDown() This method contains the logic to be executed when removing this migration. yii\db\Migration
safeUp() This method contains the logic to be executed when applying this migration. yii\db\Migration
smallInteger() Creates a smallint column. yii\db\SchemaBuilderTrait
string() Creates a string column. yii\db\SchemaBuilderTrait
text() Creates a text column. yii\db\SchemaBuilderTrait
time() Creates a time column. yii\db\SchemaBuilderTrait
timestamp() Creates a timestamp column. yii\db\SchemaBuilderTrait
tinyInteger() Creates a tinyint column. If tinyint is not supported by the DBMS, smallint will be used. yii\db\SchemaBuilderTrait
trigger() Triggers an event. yii\base\Component
truncateTable() Builds and executes a SQL statement for truncating a DB table. yii\db\Migration
up() This method contains the logic to be executed when applying this migration. yii\db\Migration
update() Creates and executes an UPDATE SQL statement. yii\db\Migration
upsert() Creates and executes a command to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do. yii\db\Migration

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
beginCommand() Prepares for a command to be executed, and outputs to the console. yii\db\Migration
endCommand() Finalizes after the command has been executed, and outputs to the console the time elapsed. yii\db\Migration
getDb() yii\db\Migration

Property Details

$compact public property (available since version 2.0.13)

Indicates whether the console output should be compacted. If this is set to true, the individual commands ran within the migration will not be output to the console. Default is false, in other words the output is fully verbose by default.

public boolean $compact false
$db public property

The DB connection object or the application component ID of the DB connection that this migration should work with. Starting from version 2.0.2, this can also be a configuration array for creating the object.

Note that when a Migration object is created by the migrate command, this property will be overwritten by the command. If you do not want to use the DB connection provided by the command, you may override the init() method like the following:

public function init()
{
    $this->db = 'db2';
    parent::init();
}
$maxSqlOutputLength public property (available since version 2.0.13)

Max number of characters of the SQL outputted. Useful for reduction of long statements and making console output more compact.

Method Details

addColumn() public method

Builds and executes a SQL statement for adding a new DB column.

public void addColumn ( $table, $column, $type )
$table string

The table that the new column will be added to. The table name will be properly quoted by the method.

$column string

The name of the new column. The name will be properly quoted by the method.

$type string

The column type. The yii\db\QueryBuilder::getColumnType() method will be invoked to convert abstract column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.

addCommentOnColumn() public method (available since version 2.0.8)

Builds and execute a SQL statement for adding comment to column.

public void addCommentOnColumn ( $table, $column, $comment )
$table string

The table whose column is to be commented. The table name will be properly quoted by the method.

$column string

The name of the column to be commented. The column name will be properly quoted by the method.

$comment string

The text of the comment to be added. The comment will be properly quoted by the method.

addCommentOnTable() public method (available since version 2.0.8)

Builds a SQL statement for adding comment to table.

public void addCommentOnTable ( $table, $comment )
$table string

The table to be commented. The table name will be properly quoted by the method.

$comment string

The text of the comment to be added. The comment will be properly quoted by the method.

addForeignKey() public method

Builds a SQL statement for adding a foreign key constraint to an existing table.

The method will properly quote the table and column names.

public void addForeignKey ( $name, $table, $columns, $refTable, $refColumns, $delete null, $update null )
$name string

The name of the foreign key constraint.

$table string

The table that the foreign key constraint will be added to.

$columns string|array

The name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas or use an array.

$refTable string

The table that the foreign key references to.

$refColumns string|array

The name of the column that the foreign key references to. If there are multiple columns, separate them with commas or use an array.

$delete string

The ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL

$update string

The ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL

addPrimaryKey() public method

Builds and executes a SQL statement for creating a primary key.

The method will properly quote the table and column names.

public void addPrimaryKey ( $name, $table, $columns )
$name string

The name of the primary key constraint.

$table string

The table that the primary key constraint will be added to.

$columns string|array

Comma separated string or array of columns that the primary key will consist of.

alterColumn() public method

Builds and executes a SQL statement for changing the definition of a column.

public void alterColumn ( $table, $column, $type )
$table string

The table whose column is to be changed. The table name will be properly quoted by the method.

$column string

The name of the column to be changed. The name will be properly quoted by the method.

$type string

The new column type. The yii\db\QueryBuilder::getColumnType() method will be invoked to convert abstract column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.

batchInsert() public method

Creates and executes a batch INSERT SQL statement.

The method will properly escape the column names, and bind the values to be inserted.

public void batchInsert ( $table, $columns, $rows )
$table string

The table that new rows will be inserted into.

$columns array

The column names.

$rows array

The rows to be batch inserted into the table

beginCommand() protected method (available since version 2.0.13)

Prepares for a command to be executed, and outputs to the console.

protected float beginCommand ( $description )
$description string

The description for the command, to be output to the console.

return float

The time before the command is executed, for the time elapsed to be calculated.

createIndex() public method

Builds and executes a SQL statement for creating a new index.

public void createIndex ( $name, $table, $columns, $unique false )
$name string

The name of the index. The name will be properly quoted by the method.

$table string

The table that the new index will be created for. The table name will be properly quoted by the method.

$columns string|array

The column(s) that should be included in the index. If there are multiple columns, please separate them by commas or use an array. Each column name will be properly quoted by the method. Quoting will be skipped for column names that include a left parenthesis "(".

$unique boolean

Whether to add UNIQUE constraint on the created index.

createTable() public method

Builds and executes a SQL statement for creating a new DB table.

The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'), where name stands for a column name which will be properly quoted by the method, and definition stands for the column type which can contain an abstract DB type.

The yii\db\QueryBuilder::getColumnType() method will be invoked to convert any abstract type into a physical one.

If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly put into the generated SQL.

public void createTable ( $table, $columns, $options null )
$table string

The name of the table to be created. The name will be properly quoted by the method.

$columns array

The columns (name => definition) in the new table.

$options string

Additional SQL fragment that will be appended to the generated SQL.

delete() public method

Creates and executes a DELETE SQL statement.

public void delete ( $table, $condition '', $params = [] )
$table string

The table where the data will be deleted from.

$condition array|string

The conditions that will be put in the WHERE part. Please refer to yii\db\Query::where() on how to specify conditions.

$params array

The parameters to be bound to the query.

down() public method

This method contains the logic to be executed when removing this migration.

The default implementation throws an exception indicating the migration cannot be removed. Child classes may override this method if the corresponding migrations can be removed.

public boolean down ( )
return boolean

Return a false value to indicate the migration fails and should not proceed further. All other return values mean the migration succeeds.

dropColumn() public method

Builds and executes a SQL statement for dropping a DB column.

public void dropColumn ( $table, $column )
$table string

The table whose column is to be dropped. The name will be properly quoted by the method.

$column string

The name of the column to be dropped. The name will be properly quoted by the method.

dropCommentFromColumn() public method (available since version 2.0.8)

Builds and execute a SQL statement for dropping comment from column.

public void dropCommentFromColumn ( $table, $column )
$table string

The table whose column is to be commented. The table name will be properly quoted by the method.

$column string

The name of the column to be commented. The column name will be properly quoted by the method.

dropCommentFromTable() public method (available since version 2.0.8)

Builds a SQL statement for dropping comment from table.

public void dropCommentFromTable ( $table )
$table string

The table whose column is to be commented. The table name will be properly quoted by the method.

dropForeignKey() public method

Builds a SQL statement for dropping a foreign key constraint.

public void dropForeignKey ( $name, $table )
$name string

The name of the foreign key constraint to be dropped. The name will be properly quoted by the method.

$table string

The table whose foreign is to be dropped. The name will be properly quoted by the method.

dropIndex() public method

Builds and executes a SQL statement for dropping an index.

public void dropIndex ( $name, $table )
$name string

The name of the index to be dropped. The name will be properly quoted by the method.

$table string

The table whose index is to be dropped. The name will be properly quoted by the method.

dropPrimaryKey() public method

Builds and executes a SQL statement for dropping a primary key.

public void dropPrimaryKey ( $name, $table )
$name string

The name of the primary key constraint to be removed.

$table string

The table that the primary key constraint will be removed from.

dropTable() public method

Builds and executes a SQL statement for dropping a DB table.

public void dropTable ( $table )
$table string

The table to be dropped. The name will be properly quoted by the method.

endCommand() protected method (available since version 2.0.13)

Finalizes after the command has been executed, and outputs to the console the time elapsed.

protected void endCommand ( $time )
$time float

The time before the command was executed.

execute() public method

Executes a SQL statement.

This method executes the specified SQL statement using $db.

public void execute ( $sql, $params = [] )
$sql string

The SQL statement to be executed

$params array

Input parameters (name => value) for the SQL execution. See yii\db\Command::execute() for more details.

getDb() protected method (available since version 2.0.6)

protected void getDb ( )
init() public method

Initializes the migration.

This method will set $db to be the 'db' application component, if it is null.

public void init ( )
insert() public method

Creates and executes an INSERT SQL statement.

The method will properly escape the column names, and bind the values to be inserted.

public void insert ( $table, $columns )
$table string

The table that new rows will be inserted into.

$columns array

The column data (name => value) to be inserted into the table.

renameColumn() public method

Builds and executes a SQL statement for renaming a column.

public void renameColumn ( $table, $name, $newName )
$table string

The table whose column is to be renamed. The name will be properly quoted by the method.

$name string

The old name of the column. The name will be properly quoted by the method.

$newName string

The new name of the column. The name will be properly quoted by the method.

renameTable() public method

Builds and executes a SQL statement for renaming a DB table.

public void renameTable ( $table, $newName )
$table string

The table to be renamed. The name will be properly quoted by the method.

$newName string

The new table name. The name will be properly quoted by the method.

safeDown() public method

This method contains the logic to be executed when removing this migration.

This method differs from down() in that the DB logic implemented here will be enclosed within a DB transaction. Child classes may implement this method instead of down() if the DB logic needs to be within a transaction.

Note: Not all DBMS support transactions. And some DB queries cannot be put into a transaction. For some examples, please refer to implicit commit.

public boolean safeDown ( )
return boolean

Return a false value to indicate the migration fails and should not proceed further. All other return values mean the migration succeeds.

safeUp() public method

This method contains the logic to be executed when applying this migration.

This method differs from up() in that the DB logic implemented here will be enclosed within a DB transaction. Child classes may implement this method instead of up() if the DB logic needs to be within a transaction.

Note: Not all DBMS support transactions. And some DB queries cannot be put into a transaction. For some examples, please refer to implicit commit.

public boolean safeUp ( )
return boolean

Return a false value to indicate the migration fails and should not proceed further. All other return values mean the migration succeeds.

truncateTable() public method

Builds and executes a SQL statement for truncating a DB table.

public void truncateTable ( $table )
$table string

The table to be truncated. The name will be properly quoted by the method.

up() public method

This method contains the logic to be executed when applying this migration.

Child classes may override this method to provide actual migration logic.

public boolean up ( )
return boolean

Return a false value to indicate the migration fails and should not proceed further. All other return values mean the migration succeeds.

update() public method

Creates and executes an UPDATE SQL statement.

The method will properly escape the column names and bind the values to be updated.

public void update ( $table, $columns, $condition '', $params = [] )
$table string

The table to be updated.

$columns array

The column data (name => value) to be updated.

$condition array|string

The conditions that will be put in the WHERE part. Please refer to yii\db\Query::where() on how to specify conditions.

$params array

The parameters to be bound to the query.

upsert() public method (available since version 2.0.14)

Creates and executes a command to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do.

The method will properly escape the column names, and bind the values to be inserted.

public $this upsert ( $table, $insertColumns, $updateColumns true, $params = [] )
$table string

The table that new rows will be inserted into/updated in.

$insertColumns array|yii\db\Query

The column data (name => value) to be inserted into the table or instance of yii\db\Query to perform INSERT INTO ... SELECT SQL statement.

$updateColumns array|boolean

The column data (name => value) to be updated if they already exist. If true is passed, the column data will be updated to match the insert column data. If false is passed, no update will be performed if the column data already exists.

$params array

The parameters to be bound to the command.

return $this

The command object itself.