Migration.php 18.2 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8 9
namespace yii\db;

w  
Qiang Xue committed
10
/**
Qiang Xue committed
11
 * Migration is the base class for representing a database migration.
w  
Qiang Xue committed
12
 *
13
 * Migration is designed to be used together with the "yii migrate" command.
w  
Qiang Xue committed
14
 *
Qiang Xue committed
15
 * Each child class of Migration represents an individual database migration which
w  
Qiang Xue committed
16 17
 * is identified by the child class name.
 *
Qiang Xue committed
18 19
 * Within each migration, the [[up()]] method should be overwritten to contain the logic
 * for "upgrading" the database; while the [[down()]] method for the "downgrading"
20
 * logic. The "yii migrate" command manages all available migrations in an application.
w  
Qiang Xue committed
21
 *
Qiang Xue committed
22 23 24 25 26 27 28 29
 * If the database supports transactions, you may also overwrite [[safeUp()]] and
 * [[safeDown()]] so that if anything wrong happens during the upgrading or downgrading,
 * the whole migration can be reverted in a whole.
 *
 * 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 [[Command]], these methods will display extra
w  
Qiang Xue committed
30 31 32 33
 * information showing the method parameters and execution time, which may be useful when
 * applying migrations.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Alexander Makarov committed
34
 * @since 2.0
w  
Qiang Xue committed
35
 */
Qiang Xue committed
36
class Migration extends \yii\base\Component
w  
Qiang Xue committed
37
{
Qiang Xue committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51
	/**
	 * @var Connection the database connection that this migration should work with.
	 * If not set, it will be initialized as the 'db' application component.
	 */
	public $db;

	/**
	 * Initializes the migration.
	 * This method will set [[db]] to be the 'db' application component, if it is null.
	 */
	public function init()
	{
		parent::init();
		if ($this->db === null) {
Qiang Xue committed
52
			$this->db = \Yii::$app->getComponent('db');
Qiang Xue committed
53 54
		}
	}
w  
Qiang Xue committed
55 56 57

	/**
	 * This method contains the logic to be executed when applying this migration.
Qiang Xue committed
58 59 60
	 * Child classes may overwrite this method to provide actual migration logic.
	 * @return boolean return a false value to indicate the migration fails
	 * and should not proceed further. All other return values mean the migration succeeds.
w  
Qiang Xue committed
61 62 63
	 */
	public function up()
	{
Qiang Xue committed
64 65
		$transaction = $this->db->beginTransaction();
		try {
Qiang Xue committed
66
			if ($this->safeUp() === false) {
67
				$transaction->rollBack();
w  
Qiang Xue committed
68 69 70
				return false;
			}
			$transaction->commit();
Qiang Xue committed
71
		} catch (\Exception $e) {
w  
Qiang Xue committed
72 73
			echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
			echo $e->getTraceAsString() . "\n";
74
			$transaction->rollBack();
w  
Qiang Xue committed
75 76
			return false;
		}
Qiang Xue committed
77
		return null;
w  
Qiang Xue committed
78 79 80 81 82 83
	}

	/**
	 * 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.
Qiang Xue committed
84 85
	 * @return boolean return a false value to indicate the migration fails
	 * and should not proceed further. All other return values mean the migration succeeds.
w  
Qiang Xue committed
86 87 88
	 */
	public function down()
	{
Qiang Xue committed
89 90
		$transaction = $this->db->beginTransaction();
		try {
Qiang Xue committed
91
			if ($this->safeDown() === false) {
92
				$transaction->rollBack();
w  
Qiang Xue committed
93 94 95
				return false;
			}
			$transaction->commit();
Qiang Xue committed
96
		} catch (\Exception $e) {
w  
Qiang Xue committed
97 98
			echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
			echo $e->getTraceAsString() . "\n";
99
			$transaction->rollBack();
w  
Qiang Xue committed
100 101
			return false;
		}
Qiang Xue committed
102
		return null;
w  
Qiang Xue committed
103 104 105 106
	}

	/**
	 * This method contains the logic to be executed when applying this migration.
Qiang Xue committed
107
	 * This method differs from [[up()]] in that the DB logic implemented here will
w  
Qiang Xue committed
108
	 * be enclosed within a DB transaction.
Qiang Xue committed
109
	 * Child classes may implement this method instead of [[up()]] if the DB logic
w  
Qiang Xue committed
110
	 * needs to be within a transaction.
Qiang Xue committed
111 112
	 * @return boolean return a false value to indicate the migration fails
	 * and should not proceed further. All other return values mean the migration succeeds.
w  
Qiang Xue committed
113 114 115 116 117 118 119
	 */
	public function safeUp()
	{
	}

	/**
	 * This method contains the logic to be executed when removing this migration.
Qiang Xue committed
120
	 * This method differs from [[down()]] in that the DB logic implemented here will
w  
Qiang Xue committed
121
	 * be enclosed within a DB transaction.
Qiang Xue committed
122
	 * Child classes may implement this method instead of [[up()]] if the DB logic
w  
Qiang Xue committed
123
	 * needs to be within a transaction.
Qiang Xue committed
124 125
	 * @return boolean return a false value to indicate the migration fails
	 * and should not proceed further. All other return values mean the migration succeeds.
w  
Qiang Xue committed
126 127 128 129 130 131 132
	 */
	public function safeDown()
	{
	}

	/**
	 * Executes a SQL statement.
Qiang Xue committed
133
	 * This method executes the specified SQL statement using [[db]].
w  
Qiang Xue committed
134
	 * @param string $sql the SQL statement to be executed
resurtm committed
135 136
	 * @param array $params input parameters (name => value) for the SQL execution.
	 * See [[Command::execute()]] for more details.
w  
Qiang Xue committed
137
	 */
Alexander Makarov committed
138
	public function execute($sql, $params = [])
w  
Qiang Xue committed
139 140 141
	{
		echo "    > execute SQL: $sql ...";
		$time = microtime(true);
Qiang Xue committed
142
		$this->db->createCommand($sql)->execute($params);
w  
Qiang Xue committed
143 144 145 146 147 148 149
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Creates and executes an INSERT SQL statement.
	 * The method will properly escape the column names, and bind the values to be inserted.
	 * @param string $table the table that new rows will be inserted into.
resurtm committed
150
	 * @param array $columns the column data (name => value) to be inserted into the table.
w  
Qiang Xue committed
151 152 153 154 155
	 */
	public function insert($table, $columns)
	{
		echo "    > insert into $table ...";
		$time = microtime(true);
Qiang Xue committed
156
		$this->db->createCommand()->insert($table, $columns)->execute();
w  
Qiang Xue committed
157 158 159
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
	/**
	 * Creates and executes an batch INSERT SQL statement.
	 * The method will properly escape the column names, and bind the values to be inserted.
	 * @param string $table the table that new rows will be inserted into.
	 * @param array $columns the column names.
	 * @param array $rows the rows to be batch inserted into the table
	 */
	public function batchInsert($table, $columns, $rows)
	{
		echo "    > insert into $table ...";
		$time = microtime(true);
		$this->db->createCommand()->batchInsert($table, $columns, $rows)->execute();
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

w  
Qiang Xue committed
175 176 177 178
	/**
	 * Creates and executes an UPDATE SQL statement.
	 * The method will properly escape the column names and bind the values to be updated.
	 * @param string $table the table to be updated.
resurtm committed
179
	 * @param array $columns the column data (name => value) to be updated.
180
	 * @param array|string $condition the conditions that will be put in the WHERE part. Please
Qiang Xue committed
181
	 * refer to [[Query::where()]] on how to specify conditions.
w  
Qiang Xue committed
182 183
	 * @param array $params the parameters to be bound to the query.
	 */
Alexander Makarov committed
184
	public function update($table, $columns, $condition = '', $params = [])
w  
Qiang Xue committed
185 186 187
	{
		echo "    > update $table ...";
		$time = microtime(true);
Qiang Xue committed
188
		$this->db->createCommand()->update($table, $columns, $condition, $params)->execute();
w  
Qiang Xue committed
189 190 191 192 193 194
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Creates and executes a DELETE SQL statement.
	 * @param string $table the table where the data will be deleted from.
195
	 * @param array|string $condition the conditions that will be put in the WHERE part. Please
Qiang Xue committed
196
	 * refer to [[Query::where()]] on how to specify conditions.
w  
Qiang Xue committed
197 198
	 * @param array $params the parameters to be bound to the query.
	 */
Alexander Makarov committed
199
	public function delete($table, $condition = '', $params = [])
w  
Qiang Xue committed
200 201 202
	{
		echo "    > delete from $table ...";
		$time = microtime(true);
Qiang Xue committed
203
		$this->db->createCommand()->delete($table, $condition, $params)->execute();
w  
Qiang Xue committed
204 205 206 207 208 209
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for creating a new DB table.
	 *
resurtm committed
210
	 * The columns in the new  table should be specified as name-definition pairs (e.g. 'name' => 'string'),
w  
Qiang Xue committed
211 212
	 * 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.
Qiang Xue committed
213 214
	 *
	 * The [[QueryBuilder::getColumnType()]] method will be invoked to convert any abstract type into a physical one.
w  
Qiang Xue committed
215 216
	 *
	 * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
Qiang Xue committed
217
	 * put into the generated SQL.
w  
Qiang Xue committed
218 219
	 *
	 * @param string $table the name of the table to be created. The name will be properly quoted by the method.
resurtm committed
220
	 * @param array $columns the columns (name => definition) in the new table.
w  
Qiang Xue committed
221 222 223 224 225 226
	 * @param string $options additional SQL fragment that will be appended to the generated SQL.
	 */
	public function createTable($table, $columns, $options = null)
	{
		echo "    > create table $table ...";
		$time = microtime(true);
Qiang Xue committed
227
		$this->db->createCommand()->createTable($table, $columns, $options)->execute();
w  
Qiang Xue committed
228 229 230 231 232 233 234 235 236 237 238 239
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for renaming a DB table.
	 * @param string $table the table to be renamed. The name will be properly quoted by the method.
	 * @param string $newName the new table name. The name will be properly quoted by the method.
	 */
	public function renameTable($table, $newName)
	{
		echo "    > rename table $table to $newName ...";
		$time = microtime(true);
Qiang Xue committed
240
		$this->db->createCommand()->renameTable($table, $newName)->execute();
w  
Qiang Xue committed
241 242 243 244 245 246 247 248 249 250 251
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for dropping a DB table.
	 * @param string $table the table to be dropped. The name will be properly quoted by the method.
	 */
	public function dropTable($table)
	{
		echo "    > drop table $table ...";
		$time = microtime(true);
Qiang Xue committed
252
		$this->db->createCommand()->dropTable($table)->execute();
w  
Qiang Xue committed
253 254 255 256 257 258 259 260 261 262 263
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for truncating a DB table.
	 * @param string $table the table to be truncated. The name will be properly quoted by the method.
	 */
	public function truncateTable($table)
	{
		echo "    > truncate table $table ...";
		$time = microtime(true);
Qiang Xue committed
264
		$this->db->createCommand()->truncateTable($table)->execute();
w  
Qiang Xue committed
265 266 267 268 269 270 271
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for adding a new DB column.
	 * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
	 * @param string $column the name of the new column. The name will be properly quoted by the method.
Qiang Xue committed
272
	 * @param string $type the column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
w  
Qiang Xue committed
273 274 275 276 277 278 279
	 * 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'.
	 */
	public function addColumn($table, $column, $type)
	{
		echo "    > add column $column $type to table $table ...";
		$time = microtime(true);
Qiang Xue committed
280
		$this->db->createCommand()->addColumn($table, $column, $type)->execute();
w  
Qiang Xue committed
281 282 283 284 285 286 287 288 289 290 291 292
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for dropping a DB column.
	 * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
	 * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
	 */
	public function dropColumn($table, $column)
	{
		echo "    > drop column $column from table $table ...";
		$time = microtime(true);
Qiang Xue committed
293
		$this->db->createCommand()->dropColumn($table, $column)->execute();
w  
Qiang Xue committed
294 295 296 297 298 299 300 301 302 303 304 305 306
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for renaming a column.
	 * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
	 * @param string $name the old name of the column. The name will be properly quoted by the method.
	 * @param string $newName the new name of the column. The name will be properly quoted by the method.
	 */
	public function renameColumn($table, $name, $newName)
	{
		echo "    > rename column $name in table $table to $newName ...";
		$time = microtime(true);
Qiang Xue committed
307
		$this->db->createCommand()->renameColumn($table, $name, $newName)->execute();
w  
Qiang Xue committed
308 309 310 311 312 313 314
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for changing the definition of a column.
	 * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
	 * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
315
	 * @param string $type the new column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
w  
Qiang Xue committed
316 317 318 319 320 321 322
	 * 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'.
	 */
	public function alterColumn($table, $column, $type)
	{
		echo "    > alter column $column in table $table to $type ...";
		$time = microtime(true);
Qiang Xue committed
323
		$this->db->createCommand()->alterColumn($table, $column, $type)->execute();
w  
Qiang Xue committed
324 325 326
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

327 328 329 330 331 332 333 334 335
	/**
	 * Builds and executes a SQL statement for creating a primary key.
	 * The method will properly quote the table and column names.
	 * @param string $name the name of the primary key constraint.
	 * @param string $table the table that the primary key constraint will be added to.
	 * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
	 */
	public function addPrimaryKey($name, $table, $columns)
	{
Luciano Baraglia committed
336
		echo "    > add primary key $name on $table (" . (is_array($columns) ? implode(',', $columns) : $columns).") ...";
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
		$time = microtime(true);
		$this->db->createCommand()->addPrimaryKey($name, $table, $columns)->execute();
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for dropping a primary key.
	 * @param string $name the name of the primary key constraint to be removed.
	 * @param string $table the table that the primary key constraint will be removed from.
	 */
	public function dropPrimaryKey($name, $table)
	{
		echo "    > drop primary key $name ...";
		$time = microtime(true);
		$this->db->createCommand()->dropPrimaryKey($name, $table)->execute();
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

w  
Qiang Xue committed
355 356 357 358 359
	/**
	 * Builds a SQL statement for adding a foreign key constraint to an existing table.
	 * The method will properly quote the table and column names.
	 * @param string $name the name of the foreign key constraint.
	 * @param string $table the table that the foreign key constraint will be added to.
Vladimir committed
360
	 * @param string $columns 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.
w  
Qiang Xue committed
361
	 * @param string $refTable the table that the foreign key references to.
Vladimir committed
362
	 * @param string $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas or use an array.
w  
Qiang Xue committed
363 364 365 366 367
	 * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
	 * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
	 */
	public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
	{
Vladimir committed
368
		echo "    > add foreign key $name: $table (" . implode(',', (array)$columns) . ") references $refTable (" . implode(',', (array)$refColumns) . ") ...";
w  
Qiang Xue committed
369
		$time = microtime(true);
Qiang Xue committed
370
		$this->db->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute();
w  
Qiang Xue committed
371 372 373 374 375 376 377 378 379 380 381 382
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds a SQL statement for dropping a foreign key constraint.
	 * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
	 * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
	 */
	public function dropForeignKey($name, $table)
	{
		echo "    > drop foreign key $name from table $table ...";
		$time = microtime(true);
Qiang Xue committed
383
		$this->db->createCommand()->dropForeignKey($name, $table)->execute();
w  
Qiang Xue committed
384 385 386 387 388 389 390
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for creating a new index.
	 * @param string $name the name of the index. The name will be properly quoted by the method.
	 * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
Sergey Gonimar committed
391
	 * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
Vladimir committed
392
	 * by commas or use an array. The column names will be properly quoted by the method.
w  
Qiang Xue committed
393 394
	 * @param boolean $unique whether to add UNIQUE constraint on the created index.
	 */
Sergey Gonimar committed
395
	public function createIndex($name, $table, $columns, $unique = false)
w  
Qiang Xue committed
396
	{
Sergey Gonimar committed
397
		echo "    > create" . ($unique ? ' unique' : '') . " index $name on $table (" . implode(',', (array)$columns) . ") ...";
w  
Qiang Xue committed
398
		$time = microtime(true);
Sergey Gonimar committed
399
		$this->db->createCommand()->createIndex($name, $table, $columns, $unique)->execute();
w  
Qiang Xue committed
400 401 402 403 404 405 406 407 408 409 410 411
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}

	/**
	 * Builds and executes a SQL statement for dropping an index.
	 * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
	 * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
	 */
	public function dropIndex($name, $table)
	{
		echo "    > drop index $name ...";
		$time = microtime(true);
Qiang Xue committed
412
		$this->db->createCommand()->dropIndex($name, $table)->execute();
w  
Qiang Xue committed
413 414
		echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
	}
Zander Baldwin committed
415
}