Migration.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db;
  8. use yii\base\Component;
  9. use yii\di\Instance;
  10. /**
  11. * Migration is the base class for representing a database migration.
  12. *
  13. * Migration is designed to be used together with the "yii migrate" command.
  14. *
  15. * Each child class of Migration represents an individual database migration which
  16. * is identified by the child class name.
  17. *
  18. * Within each migration, the [[up()]] method should be overridden to contain the logic
  19. * for "upgrading" the database; while the [[down()]] method for the "downgrading"
  20. * logic. The "yii migrate" command manages all available migrations in an application.
  21. *
  22. * If the database supports transactions, you may also override [[safeUp()]] and
  23. * [[safeDown()]] so that if anything wrong happens during the upgrading or downgrading,
  24. * the whole migration can be reverted in a whole.
  25. *
  26. * Migration provides a set of convenient methods for manipulating database data and schema.
  27. * For example, the [[insert()]] method can be used to easily insert a row of data into
  28. * a database table; the [[createTable()]] method can be used to create a database table.
  29. * Compared with the same methods in [[Command]], these methods will display extra
  30. * information showing the method parameters and execution time, which may be useful when
  31. * applying migrations.
  32. *
  33. * For more details and usage information on Migration, see the [guide article on Migration](guide:db-migrations).
  34. *
  35. * @author Qiang Xue <qiang.xue@gmail.com>
  36. * @since 2.0
  37. */
  38. class Migration extends Component implements MigrationInterface
  39. {
  40. use SchemaBuilderTrait;
  41. /**
  42. * @var Connection|array|string the DB connection object or the application component ID of the DB connection
  43. * that this migration should work with. Starting from version 2.0.2, this can also be a configuration array
  44. * for creating the object.
  45. *
  46. * Note that when a Migration object is created by the `migrate` command, this property will be overwritten
  47. * by the command. If you do not want to use the DB connection provided by the command, you may override
  48. * the [[init()]] method like the following:
  49. *
  50. * ```php
  51. * public function init()
  52. * {
  53. * $this->db = 'db2';
  54. * parent::init();
  55. * }
  56. * ```
  57. */
  58. public $db = 'db';
  59. /**
  60. * Initializes the migration.
  61. * This method will set [[db]] to be the 'db' application component, if it is `null`.
  62. */
  63. public function init()
  64. {
  65. parent::init();
  66. $this->db = Instance::ensure($this->db, Connection::className());
  67. $this->db->getSchema()->refresh();
  68. $this->db->enableSlaves = false;
  69. }
  70. /**
  71. * @inheritdoc
  72. * @since 2.0.6
  73. */
  74. protected function getDb()
  75. {
  76. return $this->db;
  77. }
  78. /**
  79. * This method contains the logic to be executed when applying this migration.
  80. * Child classes may override this method to provide actual migration logic.
  81. * @return bool return a false value to indicate the migration fails
  82. * and should not proceed further. All other return values mean the migration succeeds.
  83. */
  84. public function up()
  85. {
  86. $transaction = $this->db->beginTransaction();
  87. try {
  88. if ($this->safeUp() === false) {
  89. $transaction->rollBack();
  90. return false;
  91. }
  92. $transaction->commit();
  93. } catch (\Exception $e) {
  94. $this->printException($e);
  95. $transaction->rollBack();
  96. return false;
  97. } catch (\Throwable $e) {
  98. $this->printException($e);
  99. $transaction->rollBack();
  100. return false;
  101. }
  102. return null;
  103. }
  104. /**
  105. * This method contains the logic to be executed when removing this migration.
  106. * The default implementation throws an exception indicating the migration cannot be removed.
  107. * Child classes may override this method if the corresponding migrations can be removed.
  108. * @return bool return a false value to indicate the migration fails
  109. * and should not proceed further. All other return values mean the migration succeeds.
  110. */
  111. public function down()
  112. {
  113. $transaction = $this->db->beginTransaction();
  114. try {
  115. if ($this->safeDown() === false) {
  116. $transaction->rollBack();
  117. return false;
  118. }
  119. $transaction->commit();
  120. } catch (\Exception $e) {
  121. $this->printException($e);
  122. $transaction->rollBack();
  123. return false;
  124. } catch (\Throwable $e) {
  125. $this->printException($e);
  126. $transaction->rollBack();
  127. return false;
  128. }
  129. return null;
  130. }
  131. /**
  132. * @param \Throwable|\Exception $e
  133. */
  134. private function printException($e)
  135. {
  136. echo 'Exception: ' . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
  137. echo $e->getTraceAsString() . "\n";
  138. }
  139. /**
  140. * This method contains the logic to be executed when applying this migration.
  141. * This method differs from [[up()]] in that the DB logic implemented here will
  142. * be enclosed within a DB transaction.
  143. * Child classes may implement this method instead of [[up()]] if the DB logic
  144. * needs to be within a transaction.
  145. * @return bool return a false value to indicate the migration fails
  146. * and should not proceed further. All other return values mean the migration succeeds.
  147. */
  148. public function safeUp()
  149. {
  150. }
  151. /**
  152. * This method contains the logic to be executed when removing this migration.
  153. * This method differs from [[down()]] in that the DB logic implemented here will
  154. * be enclosed within a DB transaction.
  155. * Child classes may implement this method instead of [[down()]] if the DB logic
  156. * needs to be within a transaction.
  157. * @return bool return a false value to indicate the migration fails
  158. * and should not proceed further. All other return values mean the migration succeeds.
  159. */
  160. public function safeDown()
  161. {
  162. }
  163. /**
  164. * Executes a SQL statement.
  165. * This method executes the specified SQL statement using [[db]].
  166. * @param string $sql the SQL statement to be executed
  167. * @param array $params input parameters (name => value) for the SQL execution.
  168. * See [[Command::execute()]] for more details.
  169. */
  170. public function execute($sql, $params = [])
  171. {
  172. echo " > execute SQL: $sql ...";
  173. $time = microtime(true);
  174. $this->db->createCommand($sql)->bindValues($params)->execute();
  175. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  176. }
  177. /**
  178. * Creates and executes an INSERT SQL statement.
  179. * The method will properly escape the column names, and bind the values to be inserted.
  180. * @param string $table the table that new rows will be inserted into.
  181. * @param array $columns the column data (name => value) to be inserted into the table.
  182. */
  183. public function insert($table, $columns)
  184. {
  185. echo " > insert into $table ...";
  186. $time = microtime(true);
  187. $this->db->createCommand()->insert($table, $columns)->execute();
  188. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  189. }
  190. /**
  191. * Creates and executes an batch INSERT SQL statement.
  192. * The method will properly escape the column names, and bind the values to be inserted.
  193. * @param string $table the table that new rows will be inserted into.
  194. * @param array $columns the column names.
  195. * @param array $rows the rows to be batch inserted into the table
  196. */
  197. public function batchInsert($table, $columns, $rows)
  198. {
  199. echo " > insert into $table ...";
  200. $time = microtime(true);
  201. $this->db->createCommand()->batchInsert($table, $columns, $rows)->execute();
  202. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  203. }
  204. /**
  205. * Creates and executes an UPDATE SQL statement.
  206. * The method will properly escape the column names and bind the values to be updated.
  207. * @param string $table the table to be updated.
  208. * @param array $columns the column data (name => value) to be updated.
  209. * @param array|string $condition the conditions that will be put in the WHERE part. Please
  210. * refer to [[Query::where()]] on how to specify conditions.
  211. * @param array $params the parameters to be bound to the query.
  212. */
  213. public function update($table, $columns, $condition = '', $params = [])
  214. {
  215. echo " > update $table ...";
  216. $time = microtime(true);
  217. $this->db->createCommand()->update($table, $columns, $condition, $params)->execute();
  218. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  219. }
  220. /**
  221. * Creates and executes a DELETE SQL statement.
  222. * @param string $table the table where the data will be deleted from.
  223. * @param array|string $condition the conditions that will be put in the WHERE part. Please
  224. * refer to [[Query::where()]] on how to specify conditions.
  225. * @param array $params the parameters to be bound to the query.
  226. */
  227. public function delete($table, $condition = '', $params = [])
  228. {
  229. echo " > delete from $table ...";
  230. $time = microtime(true);
  231. $this->db->createCommand()->delete($table, $condition, $params)->execute();
  232. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  233. }
  234. /**
  235. * Builds and executes a SQL statement for creating a new DB table.
  236. *
  237. * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
  238. * where name stands for a column name which will be properly quoted by the method, and definition
  239. * stands for the column type which can contain an abstract DB type.
  240. *
  241. * The [[QueryBuilder::getColumnType()]] method will be invoked to convert any abstract type into a physical one.
  242. *
  243. * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
  244. * put into the generated SQL.
  245. *
  246. * @param string $table the name of the table to be created. The name will be properly quoted by the method.
  247. * @param array $columns the columns (name => definition) in the new table.
  248. * @param string $options additional SQL fragment that will be appended to the generated SQL.
  249. */
  250. public function createTable($table, $columns, $options = null)
  251. {
  252. echo " > create table $table ...";
  253. $time = microtime(true);
  254. $this->db->createCommand()->createTable($table, $columns, $options)->execute();
  255. foreach ($columns as $column => $type) {
  256. if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
  257. $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
  258. }
  259. }
  260. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  261. }
  262. /**
  263. * Builds and executes a SQL statement for renaming a DB table.
  264. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  265. * @param string $newName the new table name. The name will be properly quoted by the method.
  266. */
  267. public function renameTable($table, $newName)
  268. {
  269. echo " > rename table $table to $newName ...";
  270. $time = microtime(true);
  271. $this->db->createCommand()->renameTable($table, $newName)->execute();
  272. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  273. }
  274. /**
  275. * Builds and executes a SQL statement for dropping a DB table.
  276. * @param string $table the table to be dropped. The name will be properly quoted by the method.
  277. */
  278. public function dropTable($table)
  279. {
  280. echo " > drop table $table ...";
  281. $time = microtime(true);
  282. $this->db->createCommand()->dropTable($table)->execute();
  283. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  284. }
  285. /**
  286. * Builds and executes a SQL statement for truncating a DB table.
  287. * @param string $table the table to be truncated. The name will be properly quoted by the method.
  288. */
  289. public function truncateTable($table)
  290. {
  291. echo " > truncate table $table ...";
  292. $time = microtime(true);
  293. $this->db->createCommand()->truncateTable($table)->execute();
  294. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  295. }
  296. /**
  297. * Builds and executes a SQL statement for adding a new DB column.
  298. * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
  299. * @param string $column the name of the new column. The name will be properly quoted by the method.
  300. * @param string $type the column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
  301. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  302. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  303. */
  304. public function addColumn($table, $column, $type)
  305. {
  306. echo " > add column $column $type to table $table ...";
  307. $time = microtime(true);
  308. $this->db->createCommand()->addColumn($table, $column, $type)->execute();
  309. if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
  310. $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
  311. }
  312. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  313. }
  314. /**
  315. * Builds and executes a SQL statement for dropping a DB column.
  316. * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
  317. * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
  318. */
  319. public function dropColumn($table, $column)
  320. {
  321. echo " > drop column $column from table $table ...";
  322. $time = microtime(true);
  323. $this->db->createCommand()->dropColumn($table, $column)->execute();
  324. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  325. }
  326. /**
  327. * Builds and executes a SQL statement for renaming a column.
  328. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  329. * @param string $name the old name of the column. The name will be properly quoted by the method.
  330. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  331. */
  332. public function renameColumn($table, $name, $newName)
  333. {
  334. echo " > rename column $name in table $table to $newName ...";
  335. $time = microtime(true);
  336. $this->db->createCommand()->renameColumn($table, $name, $newName)->execute();
  337. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  338. }
  339. /**
  340. * Builds and executes a SQL statement for changing the definition of a column.
  341. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  342. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  343. * @param string $type the new column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
  344. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  345. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  346. */
  347. public function alterColumn($table, $column, $type)
  348. {
  349. echo " > alter column $column in table $table to $type ...";
  350. $time = microtime(true);
  351. $this->db->createCommand()->alterColumn($table, $column, $type)->execute();
  352. if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
  353. $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
  354. }
  355. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  356. }
  357. /**
  358. * Builds and executes a SQL statement for creating a primary key.
  359. * The method will properly quote the table and column names.
  360. * @param string $name the name of the primary key constraint.
  361. * @param string $table the table that the primary key constraint will be added to.
  362. * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
  363. */
  364. public function addPrimaryKey($name, $table, $columns)
  365. {
  366. echo " > add primary key $name on $table (" . (is_array($columns) ? implode(',', $columns) : $columns) . ') ...';
  367. $time = microtime(true);
  368. $this->db->createCommand()->addPrimaryKey($name, $table, $columns)->execute();
  369. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  370. }
  371. /**
  372. * Builds and executes a SQL statement for dropping a primary key.
  373. * @param string $name the name of the primary key constraint to be removed.
  374. * @param string $table the table that the primary key constraint will be removed from.
  375. */
  376. public function dropPrimaryKey($name, $table)
  377. {
  378. echo " > drop primary key $name ...";
  379. $time = microtime(true);
  380. $this->db->createCommand()->dropPrimaryKey($name, $table)->execute();
  381. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  382. }
  383. /**
  384. * Builds a SQL statement for adding a foreign key constraint to an existing table.
  385. * The method will properly quote the table and column names.
  386. * @param string $name the name of the foreign key constraint.
  387. * @param string $table the table that the foreign key constraint will be added to.
  388. * @param string|array $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.
  389. * @param string $refTable the table that the foreign key references to.
  390. * @param string|array $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.
  391. * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  392. * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  393. */
  394. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
  395. {
  396. echo " > add foreign key $name: $table (" . implode(',', (array) $columns) . ") references $refTable (" . implode(',', (array) $refColumns) . ') ...';
  397. $time = microtime(true);
  398. $this->db->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute();
  399. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  400. }
  401. /**
  402. * Builds a SQL statement for dropping a foreign key constraint.
  403. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  404. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  405. */
  406. public function dropForeignKey($name, $table)
  407. {
  408. echo " > drop foreign key $name from table $table ...";
  409. $time = microtime(true);
  410. $this->db->createCommand()->dropForeignKey($name, $table)->execute();
  411. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  412. }
  413. /**
  414. * Builds and executes a SQL statement for creating a new index.
  415. * @param string $name the name of the index. The name will be properly quoted by the method.
  416. * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
  417. * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
  418. * by commas or use an array. Each column name will be properly quoted by the method. Quoting will be skipped for column names that
  419. * include a left parenthesis "(".
  420. * @param bool $unique whether to add UNIQUE constraint on the created index.
  421. */
  422. public function createIndex($name, $table, $columns, $unique = false)
  423. {
  424. echo ' > create' . ($unique ? ' unique' : '') . " index $name on $table (" . implode(',', (array) $columns) . ') ...';
  425. $time = microtime(true);
  426. $this->db->createCommand()->createIndex($name, $table, $columns, $unique)->execute();
  427. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  428. }
  429. /**
  430. * Builds and executes a SQL statement for dropping an index.
  431. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  432. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  433. */
  434. public function dropIndex($name, $table)
  435. {
  436. echo " > drop index $name on $table ...";
  437. $time = microtime(true);
  438. $this->db->createCommand()->dropIndex($name, $table)->execute();
  439. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  440. }
  441. /**
  442. * Builds and execute a SQL statement for adding comment to column
  443. *
  444. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  445. * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
  446. * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
  447. * @since 2.0.8
  448. */
  449. public function addCommentOnColumn($table, $column, $comment)
  450. {
  451. echo " > add comment on column $column ...";
  452. $time = microtime(true);
  453. $this->db->createCommand()->addCommentOnColumn($table, $column, $comment)->execute();
  454. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  455. }
  456. /**
  457. * Builds a SQL statement for adding comment to table
  458. *
  459. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  460. * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
  461. * @since 2.0.8
  462. */
  463. public function addCommentOnTable($table, $comment)
  464. {
  465. echo " > add comment on table $table ...";
  466. $time = microtime(true);
  467. $this->db->createCommand()->addCommentOnTable($table, $comment)->execute();
  468. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  469. }
  470. /**
  471. * Builds and execute a SQL statement for dropping comment from column
  472. *
  473. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  474. * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
  475. * @since 2.0.8
  476. */
  477. public function dropCommentFromColumn($table, $column)
  478. {
  479. echo " > drop comment from column $column ...";
  480. $time = microtime(true);
  481. $this->db->createCommand()->dropCommentFromColumn($table, $column)->execute();
  482. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  483. }
  484. /**
  485. * Builds a SQL statement for dropping comment from table
  486. *
  487. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  488. * @since 2.0.8
  489. */
  490. public function dropCommentFromTable($table)
  491. {
  492. echo " > drop comment from table $table ...";
  493. $time = microtime(true);
  494. $this->db->createCommand()->dropCommentFromTable($table)->execute();
  495. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  496. }
  497. }