You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

683 lines
25KB

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