MigrateController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. <?php
  2. /**
  3. * @author Qiang Xue <[email protected]>
  4. * @link http://www.yiiframework.com/
  5. * @copyright Copyright (c) 2008 Yii Software LLC
  6. * @license http://www.yiiframework.com/license/
  7. */
  8. namespace yii\console\controllers;
  9. use Yii;
  10. use yii\console\Exception;
  11. use yii\console\Controller;
  12. use yii\db\Connection;
  13. use yii\db\Query;
  14. use yii\helpers\ArrayHelper;
  15. /**
  16. * This command manages application migrations.
  17. *
  18. * A migration means a set of persistent changes to the application environment
  19. * that is shared among different developers. For example, in an application
  20. * backed by a database, a migration may refer to a set of changes to
  21. * the database, such as creating a new table, adding a new table column.
  22. *
  23. * This command provides support for tracking the migration history, upgrading
  24. * or downloading with migrations, and creating new migration skeletons.
  25. *
  26. * The migration history is stored in a database table named
  27. * as [[migrationTable]]. The table will be automatically created the first time
  28. * this command is executed, if it does not exist. You may also manually
  29. * create it as follows:
  30. *
  31. * ~~~
  32. * CREATE TABLE tbl_migration (
  33. * version varchar(180) PRIMARY KEY,
  34. * apply_time integer
  35. * )
  36. * ~~~
  37. *
  38. * Below are some common usages of this command:
  39. *
  40. * ~~~
  41. * # creates a new migration named 'create_user_table'
  42. * yii migrate/create create_user_table
  43. *
  44. * # applies ALL new migrations
  45. * yii migrate
  46. *
  47. * # reverts the last applied migration
  48. * yii migrate/down
  49. * ~~~
  50. *
  51. * @author Qiang Xue <[email protected]>
  52. * @since 2.0
  53. */
  54. class MigrateController extends Controller
  55. {
  56. /**
  57. * The name of the dummy migration that marks the beginning of the whole migration history.
  58. */
  59. const BASE_MIGRATION = 'm000000_000000_base';
  60. /**
  61. * @var string the default command action.
  62. */
  63. public $defaultAction = 'up';
  64. /**
  65. * @var string the directory storing the migration classes. This can be either
  66. * a path alias or a directory.
  67. */
  68. public $migrationPath = '@app/migrations';
  69. /**
  70. * @var string the name of the table for keeping applied migration information.
  71. */
  72. public $migrationTable = '{{%migration}}';
  73. /**
  74. * @var string the template file for generating new migrations.
  75. * This can be either a path alias (e.g. "@app/migrations/template.php")
  76. * or a file path.
  77. */
  78. public $templateFile = '@yii/views/migration.php';
  79. /**
  80. * @var boolean whether to execute the migration in an interactive mode.
  81. */
  82. public $interactive = true;
  83. /**
  84. * @var Connection|string the DB connection object or the application
  85. * component ID of the DB connection.
  86. */
  87. public $db = 'db';
  88. /**
  89. * Returns the names of the global options for this command.
  90. * @return array the names of the global options for this command.
  91. */
  92. public function globalOptions()
  93. {
  94. return array_merge(parent::globalOptions(), [
  95. 'migrationPath', 'migrationTable', 'db', 'templateFile', 'interactive', 'color'
  96. ]);
  97. }
  98. /**
  99. * This method is invoked right before an action is to be executed (after all possible filters.)
  100. * It checks the existence of the [[migrationPath]].
  101. * @param \yii\base\Action $action the action to be executed.
  102. * @return boolean whether the action should continue to be executed.
  103. * @throws Exception if the migration directory does not exist.
  104. */
  105. public function beforeAction($action)
  106. {
  107. if (parent::beforeAction($action)) {
  108. $path = Yii::getAlias($this->migrationPath);
  109. if (!is_dir($path)) {
  110. throw new Exception("The migration directory \"{$path}\" does not exist.");
  111. }
  112. $this->migrationPath = $path;
  113. if ($action->id !== 'create') {
  114. if (is_string($this->db)) {
  115. $this->db = Yii::$app->getComponent($this->db);
  116. }
  117. if (!$this->db instanceof Connection) {
  118. throw new Exception("The 'db' option must refer to the application component ID of a DB connection.");
  119. }
  120. }
  121. $version = Yii::getVersion();
  122. echo "Yii Migration Tool (based on Yii v{$version})\n\n";
  123. return true;
  124. } else {
  125. return false;
  126. }
  127. }
  128. /**
  129. * Upgrades the application by applying new migrations.
  130. * For example,
  131. *
  132. * ~~~
  133. * yii migrate # apply all new migrations
  134. * yii migrate 3 # apply the first 3 new migrations
  135. * ~~~
  136. *
  137. * @param integer $limit the number of new migrations to be applied. If 0, it means
  138. * applying all available new migrations.
  139. */
  140. public function actionUp($limit = 0)
  141. {
  142. $migrations = $this->getNewMigrations();
  143. if (empty($migrations)) {
  144. echo "No new migration found. Your system is up-to-date.\n";
  145. return;
  146. }
  147. $total = count($migrations);
  148. $limit = (int)$limit;
  149. if ($limit > 0) {
  150. $migrations = array_slice($migrations, 0, $limit);
  151. }
  152. $n = count($migrations);
  153. if ($n === $total) {
  154. echo "Total $n new " . ($n === 1 ? 'migration' : 'migrations') . " to be applied:\n";
  155. } else {
  156. echo "Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n";
  157. }
  158. foreach ($migrations as $migration) {
  159. echo " $migration\n";
  160. }
  161. echo "\n";
  162. if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) {
  163. foreach ($migrations as $migration) {
  164. if (!$this->migrateUp($migration)) {
  165. echo "\nMigration failed. The rest of the migrations are canceled.\n";
  166. return;
  167. }
  168. }
  169. echo "\nMigrated up successfully.\n";
  170. }
  171. }
  172. /**
  173. * Downgrades the application by reverting old migrations.
  174. * For example,
  175. *
  176. * ~~~
  177. * yii migrate/down # revert the last migration
  178. * yii migrate/down 3 # revert the last 3 migrations
  179. * ~~~
  180. *
  181. * @param integer $limit the number of migrations to be reverted. Defaults to 1,
  182. * meaning the last applied migration will be reverted.
  183. * @throws Exception if the number of the steps specified is less than 1.
  184. */
  185. public function actionDown($limit = 1)
  186. {
  187. $limit = (int)$limit;
  188. if ($limit < 1) {
  189. throw new Exception("The step argument must be greater than 0.");
  190. }
  191. $migrations = $this->getMigrationHistory($limit);
  192. if (empty($migrations)) {
  193. echo "No migration has been done before.\n";
  194. return;
  195. }
  196. $migrations = array_keys($migrations);
  197. $n = count($migrations);
  198. echo "Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n";
  199. foreach ($migrations as $migration) {
  200. echo " $migration\n";
  201. }
  202. echo "\n";
  203. if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) {
  204. foreach ($migrations as $migration) {
  205. if (!$this->migrateDown($migration)) {
  206. echo "\nMigration failed. The rest of the migrations are canceled.\n";
  207. return;
  208. }
  209. }
  210. echo "\nMigrated down successfully.\n";
  211. }
  212. }
  213. /**
  214. * Redoes the last few migrations.
  215. *
  216. * This command will first revert the specified migrations, and then apply
  217. * them again. For example,
  218. *
  219. * ~~~
  220. * yii migrate/redo # redo the last applied migration
  221. * yii migrate/redo 3 # redo the last 3 applied migrations
  222. * ~~~
  223. *
  224. * @param integer $limit the number of migrations to be redone. Defaults to 1,
  225. * meaning the last applied migration will be redone.
  226. * @throws Exception if the number of the steps specified is less than 1.
  227. */
  228. public function actionRedo($limit = 1)
  229. {
  230. $limit = (int)$limit;
  231. if ($limit < 1) {
  232. throw new Exception("The step argument must be greater than 0.");
  233. }
  234. $migrations = $this->getMigrationHistory($limit);
  235. if (empty($migrations)) {
  236. echo "No migration has been done before.\n";
  237. return;
  238. }
  239. $migrations = array_keys($migrations);
  240. $n = count($migrations);
  241. echo "Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be redone:\n";
  242. foreach ($migrations as $migration) {
  243. echo " $migration\n";
  244. }
  245. echo "\n";
  246. if ($this->confirm('Redo the above ' . ($n === 1 ? 'migration' : 'migrations') . "?")) {
  247. foreach ($migrations as $migration) {
  248. if (!$this->migrateDown($migration)) {
  249. echo "\nMigration failed. The rest of the migrations are canceled.\n";
  250. return;
  251. }
  252. }
  253. foreach (array_reverse($migrations) as $migration) {
  254. if (!$this->migrateUp($migration)) {
  255. echo "\nMigration failed. The rest of the migrations migrations are canceled.\n";
  256. return;
  257. }
  258. }
  259. echo "\nMigration redone successfully.\n";
  260. }
  261. }
  262. /**
  263. * Upgrades or downgrades till the specified version.
  264. *
  265. * This command will first revert the specified migrations, and then apply
  266. * them again. For example,
  267. *
  268. * ~~~
  269. * yii migrate/to 101129_185401 # using timestamp
  270. * yii migrate/to m101129_185401_create_user_table # using full name
  271. * ~~~
  272. *
  273. * @param string $version the version name that the application should be migrated to.
  274. * This can be either the timestamp or the full name of the migration.
  275. * @throws Exception if the version argument is invalid
  276. */
  277. public function actionTo($version)
  278. {
  279. $originalVersion = $version;
  280. if (preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/', $version, $matches)) {
  281. $version = 'm' . $matches[1];
  282. } else {
  283. throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table).");
  284. }
  285. // try migrate up
  286. $migrations = $this->getNewMigrations();
  287. foreach ($migrations as $i => $migration) {
  288. if (strpos($migration, $version . '_') === 0) {
  289. $this->actionUp($i + 1);
  290. return;
  291. }
  292. }
  293. // try migrate down
  294. $migrations = array_keys($this->getMigrationHistory(-1));
  295. foreach ($migrations as $i => $migration) {
  296. if (strpos($migration, $version . '_') === 0) {
  297. if ($i === 0) {
  298. echo "Already at '$originalVersion'. Nothing needs to be done.\n";
  299. } else {
  300. $this->actionDown($i);
  301. }
  302. return;
  303. }
  304. }
  305. throw new Exception("Unable to find the version '$originalVersion'.");
  306. }
  307. /**
  308. * Modifies the migration history to the specified version.
  309. *
  310. * No actual migration will be performed.
  311. *
  312. * ~~~
  313. * yii migrate/mark 101129_185401 # using timestamp
  314. * yii migrate/mark m101129_185401_create_user_table # using full name
  315. * ~~~
  316. *
  317. * @param string $version the version at which the migration history should be marked.
  318. * This can be either the timestamp or the full name of the migration.
  319. * @throws Exception if the version argument is invalid or the version cannot be found.
  320. */
  321. public function actionMark($version)
  322. {
  323. $originalVersion = $version;
  324. if (preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/', $version, $matches)) {
  325. $version = 'm' . $matches[1];
  326. } else {
  327. throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table).");
  328. }
  329. // try mark up
  330. $migrations = $this->getNewMigrations();
  331. foreach ($migrations as $i => $migration) {
  332. if (strpos($migration, $version . '_') === 0) {
  333. if ($this->confirm("Set migration history at $originalVersion?")) {
  334. $command = $this->db->createCommand();
  335. for ($j = 0; $j <= $i; ++$j) {
  336. $command->insert($this->migrationTable, [
  337. 'version' => $migrations[$j],
  338. 'apply_time' => time(),
  339. ])->execute();
  340. }
  341. echo "The migration history is set at $originalVersion.\nNo actual migration was performed.\n";
  342. }
  343. return;
  344. }
  345. }
  346. // try mark down
  347. $migrations = array_keys($this->getMigrationHistory(-1));
  348. foreach ($migrations as $i => $migration) {
  349. if (strpos($migration, $version . '_') === 0) {
  350. if ($i === 0) {
  351. echo "Already at '$originalVersion'. Nothing needs to be done.\n";
  352. } else {
  353. if ($this->confirm("Set migration history at $originalVersion?")) {
  354. $command = $this->db->createCommand();
  355. for ($j = 0; $j < $i; ++$j) {
  356. $command->delete($this->migrationTable, [
  357. 'version' => $migrations[$j],
  358. ])->execute();
  359. }
  360. echo "The migration history is set at $originalVersion.\nNo actual migration was performed.\n";
  361. }
  362. }
  363. return;
  364. }
  365. }
  366. throw new Exception("Unable to find the version '$originalVersion'.");
  367. }
  368. /**
  369. * Displays the migration history.
  370. *
  371. * This command will show the list of migrations that have been applied
  372. * so far. For example,
  373. *
  374. * ~~~
  375. * yii migrate/history # showing the last 10 migrations
  376. * yii migrate/history 5 # showing the last 5 migrations
  377. * yii migrate/history 0 # showing the whole history
  378. * ~~~
  379. *
  380. * @param integer $limit the maximum number of migrations to be displayed.
  381. * If it is 0, the whole migration history will be displayed.
  382. */
  383. public function actionHistory($limit = 10)
  384. {
  385. $limit = (int)$limit;
  386. $migrations = $this->getMigrationHistory($limit);
  387. if (empty($migrations)) {
  388. echo "No migration has been done before.\n";
  389. } else {
  390. $n = count($migrations);
  391. if ($limit > 0) {
  392. echo "Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n";
  393. } else {
  394. echo "Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n";
  395. }
  396. foreach ($migrations as $version => $time) {
  397. echo " (" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n";
  398. }
  399. }
  400. }
  401. /**
  402. * Displays the un-applied new migrations.
  403. *
  404. * This command will show the new migrations that have not been applied.
  405. * For example,
  406. *
  407. * ~~~
  408. * yii migrate/new # showing the first 10 new migrations
  409. * yii migrate/new 5 # showing the first 5 new migrations
  410. * yii migrate/new 0 # showing all new migrations
  411. * ~~~
  412. *
  413. * @param integer $limit the maximum number of new migrations to be displayed.
  414. * If it is 0, all available new migrations will be displayed.
  415. */
  416. public function actionNew($limit = 10)
  417. {
  418. $limit = (int)$limit;
  419. $migrations = $this->getNewMigrations();
  420. if (empty($migrations)) {
  421. echo "No new migrations found. Your system is up-to-date.\n";
  422. } else {
  423. $n = count($migrations);
  424. if ($limit > 0 && $n > $limit) {
  425. $migrations = array_slice($migrations, 0, $limit);
  426. echo "Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n";
  427. } else {
  428. echo "Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n";
  429. }
  430. foreach ($migrations as $migration) {
  431. echo " " . $migration . "\n";
  432. }
  433. }
  434. }
  435. /**
  436. * Creates a new migration.
  437. *
  438. * This command creates a new migration using the available migration template.
  439. * After using this command, developers should modify the created migration
  440. * skeleton by filling up the actual migration logic.
  441. *
  442. * ~~~
  443. * yii migrate/create create_user_table
  444. * ~~~
  445. *
  446. * @param string $name the name of the new migration. This should only contain
  447. * letters, digits and/or underscores.
  448. * @throws Exception if the name argument is invalid.
  449. */
  450. public function actionCreate($name)
  451. {
  452. if (!preg_match('/^\w+$/', $name)) {
  453. throw new Exception("The migration name should contain letters, digits and/or underscore characters only.");
  454. }
  455. $name = 'm' . gmdate('ymd_His') . '_' . $name;
  456. $file = $this->migrationPath . DIRECTORY_SEPARATOR . $name . '.php';
  457. if ($this->confirm("Create new migration '$file'?")) {
  458. $content = $this->renderFile(Yii::getAlias($this->templateFile), ['className' => $name]);
  459. file_put_contents($file, $content);
  460. echo "New migration created successfully.\n";
  461. }
  462. }
  463. /**
  464. * Upgrades with the specified migration class.
  465. * @param string $class the migration class name
  466. * @return boolean whether the migration is successful
  467. */
  468. protected function migrateUp($class)
  469. {
  470. if ($class === self::BASE_MIGRATION) {
  471. return true;
  472. }
  473. echo "*** applying $class\n";
  474. $start = microtime(true);
  475. $migration = $this->createMigration($class);
  476. if ($migration->up() !== false) {
  477. $this->db->createCommand()->insert($this->migrationTable, [
  478. 'version' => $class,
  479. 'apply_time' => time(),
  480. ])->execute();
  481. $time = microtime(true) - $start;
  482. echo "*** applied $class (time: " . sprintf("%.3f", $time) . "s)\n\n";
  483. return true;
  484. } else {
  485. $time = microtime(true) - $start;
  486. echo "*** failed to apply $class (time: " . sprintf("%.3f", $time) . "s)\n\n";
  487. return false;
  488. }
  489. }
  490. /**
  491. * Downgrades with the specified migration class.
  492. * @param string $class the migration class name
  493. * @return boolean whether the migration is successful
  494. */
  495. protected function migrateDown($class)
  496. {
  497. if ($class === self::BASE_MIGRATION) {
  498. return true;
  499. }
  500. echo "*** reverting $class\n";
  501. $start = microtime(true);
  502. $migration = $this->createMigration($class);
  503. if ($migration->down() !== false) {
  504. $this->db->createCommand()->delete($this->migrationTable, [
  505. 'version' => $class,
  506. ])->execute();
  507. $time = microtime(true) - $start;
  508. echo "*** reverted $class (time: " . sprintf("%.3f", $time) . "s)\n\n";
  509. return true;
  510. } else {
  511. $time = microtime(true) - $start;
  512. echo "*** failed to revert $class (time: " . sprintf("%.3f", $time) . "s)\n\n";
  513. return false;
  514. }
  515. }
  516. /**
  517. * Creates a new migration instance.
  518. * @param string $class the migration class name
  519. * @return \yii\db\Migration the migration instance
  520. */
  521. protected function createMigration($class)
  522. {
  523. $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
  524. require_once($file);
  525. return new $class(['db' => $this->db]);
  526. }
  527. /**
  528. * Returns the migration history.
  529. * @param integer $limit the maximum number of records in the history to be returned
  530. * @return array the migration history
  531. */
  532. protected function getMigrationHistory($limit)
  533. {
  534. if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
  535. $this->createMigrationHistoryTable();
  536. }
  537. $query = new Query;
  538. $rows = $query->select(['version', 'apply_time'])
  539. ->from($this->migrationTable)
  540. ->orderBy('version DESC')
  541. ->limit($limit)
  542. ->createCommand($this->db)
  543. ->queryAll();
  544. $history = ArrayHelper::map($rows, 'version', 'apply_time');
  545. unset($history[self::BASE_MIGRATION]);
  546. return $history;
  547. }
  548. /**
  549. * Creates the migration history table.
  550. */
  551. protected function createMigrationHistoryTable()
  552. {
  553. echo 'Creating migration history table "' . $this->migrationTable . '"...';
  554. $this->db->createCommand()->createTable($this->migrationTable, [
  555. 'version' => 'varchar(180) NOT NULL PRIMARY KEY',
  556. 'apply_time' => 'integer',
  557. ])->execute();
  558. $this->db->createCommand()->insert($this->migrationTable, [
  559. 'version' => self::BASE_MIGRATION,
  560. 'apply_time' => time(),
  561. ])->execute();
  562. echo "done.\n";
  563. }
  564. /**
  565. * Returns the migrations that are not applied.
  566. * @return array list of new migrations
  567. */
  568. protected function getNewMigrations()
  569. {
  570. $applied = [];
  571. foreach ($this->getMigrationHistory(-1) as $version => $time) {
  572. $applied[substr($version, 1, 13)] = true;
  573. }
  574. $migrations = [];
  575. $handle = opendir($this->migrationPath);
  576. while (($file = readdir($handle)) !== false) {
  577. if ($file === '.' || $file === '..') {
  578. continue;
  579. }
  580. $path = $this->migrationPath . DIRECTORY_SEPARATOR . $file;
  581. if (preg_match('/^(m(\d{6}_\d{6})_.*?)\.php$/', $file, $matches) && is_file($path) && !isset($applied[$matches[2]])) {
  582. $migrations[] = $matches[1];
  583. }
  584. }
  585. closedir($handle);
  586. sort($migrations);
  587. return $migrations;
  588. }
  589. }