BaseMigrateController.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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\base\InvalidConfigException;
  10. use yii\console\Exception;
  11. use yii\console\Controller;
  12. use yii\helpers\Console;
  13. use yii\helpers\FileHelper;
  14. use yii\helpers\StringHelper;
  15. /**
  16. * BaseMigrateController is the base class for migrate controllers.
  17. *
  18. * @author Qiang Xue <qiang.xue@gmail.com>
  19. * @since 2.0
  20. */
  21. abstract class BaseMigrateController extends Controller
  22. {
  23. /**
  24. * The name of the dummy migration that marks the beginning of the whole migration history.
  25. */
  26. const BASE_MIGRATION = 'm000000_000000_base';
  27. /**
  28. * @var string the default command action.
  29. */
  30. public $defaultAction = 'up';
  31. /**
  32. * @var string|array the directory containing the migration classes. This can be either
  33. * a [path alias](guide:concept-aliases) or a directory path.
  34. *
  35. * Migration classes located at this path should be declared without a namespace.
  36. * Use [[migrationNamespaces]] property in case you are using namespaced migrations.
  37. *
  38. * If you have set up [[migrationNamespaces]], you may set this field to `null` in order
  39. * to disable usage of migrations that are not namespaced.
  40. *
  41. * Since version 2.0.12 you may also specify an array of migration paths that should be searched for
  42. * migrations to load. This is mainly useful to support old extensions that provide migrations
  43. * without namespace and to adopt the new feature of namespaced migrations while keeping existing migrations.
  44. *
  45. * In general, to load migrations from different locations, [[migrationNamespaces]] is the preferable solution
  46. * as the migration name contains the origin of the migration in the history, which is not the case when
  47. * using multiple migration paths.
  48. *
  49. * @see $migrationNamespaces
  50. */
  51. public $migrationPath = ['@app/migrations'];
  52. /**
  53. * @var array list of namespaces containing the migration classes.
  54. *
  55. * Migration namespaces should be resolvable as a [path alias](guide:concept-aliases) if prefixed with `@`, e.g. if you specify
  56. * the namespace `app\migrations`, the code `Yii::getAlias('@app/migrations')` should be able to return
  57. * the file path to the directory this namespace refers to.
  58. * This corresponds with the [autoloading conventions](guide:concept-autoloading) of Yii.
  59. *
  60. * For example:
  61. *
  62. * ```php
  63. * [
  64. * 'app\migrations',
  65. * 'some\extension\migrations',
  66. * ]
  67. * ```
  68. *
  69. * @since 2.0.10
  70. * @see $migrationPath
  71. */
  72. public $migrationNamespaces = [];
  73. /**
  74. * @var string the template file for generating new migrations.
  75. * This can be either a [path alias](guide:concept-aliases) (e.g. "@app/migrations/template.php")
  76. * or a file path.
  77. */
  78. public $templateFile;
  79. /**
  80. * @inheritdoc
  81. */
  82. public function options($actionID)
  83. {
  84. return array_merge(
  85. parent::options($actionID),
  86. ['migrationPath', 'migrationNamespaces'], // global for all actions
  87. $actionID === 'create' ? ['templateFile'] : [] // action create
  88. );
  89. }
  90. /**
  91. * This method is invoked right before an action is to be executed (after all possible filters.)
  92. * It checks the existence of the [[migrationPath]].
  93. * @param \yii\base\Action $action the action to be executed.
  94. * @throws InvalidConfigException if directory specified in migrationPath doesn't exist and action isn't "create".
  95. * @return bool whether the action should continue to be executed.
  96. */
  97. public function beforeAction($action)
  98. {
  99. if (parent::beforeAction($action)) {
  100. if (empty($this->migrationNamespaces) && empty($this->migrationPath)) {
  101. throw new InvalidConfigException('At least one of `migrationPath` or `migrationNamespaces` should be specified.');
  102. }
  103. foreach ($this->migrationNamespaces as $key => $value) {
  104. $this->migrationNamespaces[$key] = trim($value, '\\');
  105. }
  106. if (is_array($this->migrationPath)) {
  107. foreach($this->migrationPath as $i => $path) {
  108. $this->migrationPath[$i] = Yii::getAlias($path);
  109. }
  110. } elseif ($this->migrationPath !== null) {
  111. $path = Yii::getAlias($this->migrationPath);
  112. if (!is_dir($path)) {
  113. if ($action->id !== 'create') {
  114. throw new InvalidConfigException("Migration failed. Directory specified in migrationPath doesn't exist: {$this->migrationPath}");
  115. }
  116. FileHelper::createDirectory($path);
  117. }
  118. $this->migrationPath = $path;
  119. }
  120. $version = Yii::getVersion();
  121. $this->stdout("Yii Migration Tool (based on Yii v{$version})\n\n");
  122. return true;
  123. } else {
  124. return false;
  125. }
  126. }
  127. /**
  128. * Upgrades the application by applying new migrations.
  129. * For example,
  130. *
  131. * ```
  132. * yii migrate # apply all new migrations
  133. * yii migrate 3 # apply the first 3 new migrations
  134. * ```
  135. *
  136. * @param int $limit the number of new migrations to be applied. If 0, it means
  137. * applying all available new migrations.
  138. *
  139. * @return int the status of the action execution. 0 means normal, other values mean abnormal.
  140. */
  141. public function actionUp($limit = 0)
  142. {
  143. $migrations = $this->getNewMigrations();
  144. if (empty($migrations)) {
  145. $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
  146. return self::EXIT_CODE_NORMAL;
  147. }
  148. $total = count($migrations);
  149. $limit = (int) $limit;
  150. if ($limit > 0) {
  151. $migrations = array_slice($migrations, 0, $limit);
  152. }
  153. $n = count($migrations);
  154. if ($n === $total) {
  155. $this->stdout("Total $n new " . ($n === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
  156. } else {
  157. $this->stdout("Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
  158. }
  159. foreach ($migrations as $migration) {
  160. $this->stdout("\t$migration\n");
  161. }
  162. $this->stdout("\n");
  163. $applied = 0;
  164. if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
  165. foreach ($migrations as $migration) {
  166. if (!$this->migrateUp($migration)) {
  167. $this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') ." applied.\n", Console::FG_RED);
  168. $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
  169. return self::EXIT_CODE_ERROR;
  170. }
  171. $applied++;
  172. }
  173. $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') ." applied.\n", Console::FG_GREEN);
  174. $this->stdout("\nMigrated up successfully.\n", Console::FG_GREEN);
  175. }
  176. }
  177. /**
  178. * Downgrades the application by reverting old migrations.
  179. * For example,
  180. *
  181. * ```
  182. * yii migrate/down # revert the last migration
  183. * yii migrate/down 3 # revert the last 3 migrations
  184. * yii migrate/down all # revert all migrations
  185. * ```
  186. *
  187. * @param int $limit the number of migrations to be reverted. Defaults to 1,
  188. * meaning the last applied migration will be reverted.
  189. * @throws Exception if the number of the steps specified is less than 1.
  190. *
  191. * @return int the status of the action execution. 0 means normal, other values mean abnormal.
  192. */
  193. public function actionDown($limit = 1)
  194. {
  195. if ($limit === 'all') {
  196. $limit = null;
  197. } else {
  198. $limit = (int) $limit;
  199. if ($limit < 1) {
  200. throw new Exception('The step argument must be greater than 0.');
  201. }
  202. }
  203. $migrations = $this->getMigrationHistory($limit);
  204. if (empty($migrations)) {
  205. $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
  206. return self::EXIT_CODE_NORMAL;
  207. }
  208. $migrations = array_keys($migrations);
  209. $n = count($migrations);
  210. $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n", Console::FG_YELLOW);
  211. foreach ($migrations as $migration) {
  212. $this->stdout("\t$migration\n");
  213. }
  214. $this->stdout("\n");
  215. $reverted = 0;
  216. if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
  217. foreach ($migrations as $migration) {
  218. if (!$this->migrateDown($migration)) {
  219. $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') ." reverted.\n", Console::FG_RED);
  220. $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
  221. return self::EXIT_CODE_ERROR;
  222. }
  223. $reverted++;
  224. }
  225. $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') ." reverted.\n", Console::FG_GREEN);
  226. $this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN);
  227. }
  228. }
  229. /**
  230. * Redoes the last few migrations.
  231. *
  232. * This command will first revert the specified migrations, and then apply
  233. * them again. For example,
  234. *
  235. * ```
  236. * yii migrate/redo # redo the last applied migration
  237. * yii migrate/redo 3 # redo the last 3 applied migrations
  238. * yii migrate/redo all # redo all migrations
  239. * ```
  240. *
  241. * @param int $limit the number of migrations to be redone. Defaults to 1,
  242. * meaning the last applied migration will be redone.
  243. * @throws Exception if the number of the steps specified is less than 1.
  244. *
  245. * @return int the status of the action execution. 0 means normal, other values mean abnormal.
  246. */
  247. public function actionRedo($limit = 1)
  248. {
  249. if ($limit === 'all') {
  250. $limit = null;
  251. } else {
  252. $limit = (int) $limit;
  253. if ($limit < 1) {
  254. throw new Exception('The step argument must be greater than 0.');
  255. }
  256. }
  257. $migrations = $this->getMigrationHistory($limit);
  258. if (empty($migrations)) {
  259. $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
  260. return self::EXIT_CODE_NORMAL;
  261. }
  262. $migrations = array_keys($migrations);
  263. $n = count($migrations);
  264. $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be redone:\n", Console::FG_YELLOW);
  265. foreach ($migrations as $migration) {
  266. $this->stdout("\t$migration\n");
  267. }
  268. $this->stdout("\n");
  269. if ($this->confirm('Redo the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
  270. foreach ($migrations as $migration) {
  271. if (!$this->migrateDown($migration)) {
  272. $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
  273. return self::EXIT_CODE_ERROR;
  274. }
  275. }
  276. foreach (array_reverse($migrations) as $migration) {
  277. if (!$this->migrateUp($migration)) {
  278. $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
  279. return self::EXIT_CODE_ERROR;
  280. }
  281. }
  282. $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') ." redone.\n", Console::FG_GREEN);
  283. $this->stdout("\nMigration redone successfully.\n", Console::FG_GREEN);
  284. }
  285. }
  286. /**
  287. * Upgrades or downgrades till the specified version.
  288. *
  289. * Can also downgrade versions to the certain apply time in the past by providing
  290. * a UNIX timestamp or a string parseable by the strtotime() function. This means
  291. * that all the versions applied after the specified certain time would be reverted.
  292. *
  293. * This command will first revert the specified migrations, and then apply
  294. * them again. For example,
  295. *
  296. * ```
  297. * yii migrate/to 101129_185401 # using timestamp
  298. * yii migrate/to m101129_185401_create_user_table # using full name
  299. * yii migrate/to 1392853618 # using UNIX timestamp
  300. * yii migrate/to "2014-02-15 13:00:50" # using strtotime() parseable string
  301. * yii migrate/to app\migrations\M101129185401CreateUser # using full namespace name
  302. * ```
  303. *
  304. * @param string $version either the version name or the certain time value in the past
  305. * that the application should be migrated to. This can be either the timestamp,
  306. * the full name of the migration, the UNIX timestamp, or the parseable datetime
  307. * string.
  308. * @throws Exception if the version argument is invalid.
  309. */
  310. public function actionTo($version)
  311. {
  312. if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
  313. $this->migrateToVersion($namespaceVersion);
  314. } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
  315. $this->migrateToVersion($migrationName);
  316. } elseif ((string) (int) $version == $version) {
  317. $this->migrateToTime($version);
  318. } elseif (($time = strtotime($version)) !== false) {
  319. $this->migrateToTime($time);
  320. } else {
  321. 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 the full namespaced name of a migration (e.g. app\\migrations\\M101129185401CreateUserTable),\n a UNIX timestamp (e.g. 1392853000), or a datetime string parseable\nby the strtotime() function (e.g. 2014-02-15 13:00:50).");
  322. }
  323. }
  324. /**
  325. * Modifies the migration history to the specified version.
  326. *
  327. * No actual migration will be performed.
  328. *
  329. * ```
  330. * yii migrate/mark 101129_185401 # using timestamp
  331. * yii migrate/mark m101129_185401_create_user_table # using full name
  332. * yii migrate/to app\migrations\M101129185401CreateUser # using full namespace name
  333. * ```
  334. *
  335. * @param string $version the version at which the migration history should be marked.
  336. * This can be either the timestamp or the full name of the migration.
  337. * @return int CLI exit code
  338. * @throws Exception if the version argument is invalid or the version cannot be found.
  339. */
  340. public function actionMark($version)
  341. {
  342. $originalVersion = $version;
  343. if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
  344. $version = $namespaceVersion;
  345. } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
  346. $version = $migrationName;
  347. } else {
  348. 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)\nor the full name of a namespaced migration (e.g. app\\migrations\\M101129185401CreateUserTable).");
  349. }
  350. // try mark up
  351. $migrations = $this->getNewMigrations();
  352. foreach ($migrations as $i => $migration) {
  353. if (strpos($migration, $version) === 0) {
  354. if ($this->confirm("Set migration history at $originalVersion?")) {
  355. for ($j = 0; $j <= $i; ++$j) {
  356. $this->addMigrationHistory($migrations[$j]);
  357. }
  358. $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
  359. }
  360. return self::EXIT_CODE_NORMAL;
  361. }
  362. }
  363. // try mark down
  364. $migrations = array_keys($this->getMigrationHistory(null));
  365. foreach ($migrations as $i => $migration) {
  366. if (strpos($migration, $version) === 0) {
  367. if ($i === 0) {
  368. $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
  369. } else {
  370. if ($this->confirm("Set migration history at $originalVersion?")) {
  371. for ($j = 0; $j < $i; ++$j) {
  372. $this->removeMigrationHistory($migrations[$j]);
  373. }
  374. $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
  375. }
  376. }
  377. return self::EXIT_CODE_NORMAL;
  378. }
  379. }
  380. throw new Exception("Unable to find the version '$originalVersion'.");
  381. }
  382. /**
  383. * Checks if given migration version specification matches namespaced migration name.
  384. * @param string $rawVersion raw version specification received from user input.
  385. * @return string|false actual migration version, `false` - if not match.
  386. * @since 2.0.10
  387. */
  388. private function extractNamespaceMigrationVersion($rawVersion)
  389. {
  390. if (preg_match('/^\\\\?([\w_]+\\\\)+m(\d{6}_?\d{6})(\D.*)?$/is', $rawVersion, $matches)) {
  391. return trim($rawVersion, '\\');
  392. }
  393. return false;
  394. }
  395. /**
  396. * Checks if given migration version specification matches migration base name.
  397. * @param string $rawVersion raw version specification received from user input.
  398. * @return string|false actual migration version, `false` - if not match.
  399. * @since 2.0.10
  400. */
  401. private function extractMigrationVersion($rawVersion)
  402. {
  403. if (preg_match('/^m?(\d{6}_?\d{6})(\D.*)?$/is', $rawVersion, $matches)) {
  404. return 'm' . $matches[1];
  405. }
  406. return false;
  407. }
  408. /**
  409. * Displays the migration history.
  410. *
  411. * This command will show the list of migrations that have been applied
  412. * so far. For example,
  413. *
  414. * ```
  415. * yii migrate/history # showing the last 10 migrations
  416. * yii migrate/history 5 # showing the last 5 migrations
  417. * yii migrate/history all # showing the whole history
  418. * ```
  419. *
  420. * @param int $limit the maximum number of migrations to be displayed.
  421. * If it is "all", the whole migration history will be displayed.
  422. * @throws \yii\console\Exception if invalid limit value passed
  423. */
  424. public function actionHistory($limit = 10)
  425. {
  426. if ($limit === 'all') {
  427. $limit = null;
  428. } else {
  429. $limit = (int) $limit;
  430. if ($limit < 1) {
  431. throw new Exception('The limit must be greater than 0.');
  432. }
  433. }
  434. $migrations = $this->getMigrationHistory($limit);
  435. if (empty($migrations)) {
  436. $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
  437. } else {
  438. $n = count($migrations);
  439. if ($limit > 0) {
  440. $this->stdout("Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
  441. } else {
  442. $this->stdout("Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n", Console::FG_YELLOW);
  443. }
  444. foreach ($migrations as $version => $time) {
  445. $this->stdout("\t(" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n");
  446. }
  447. }
  448. }
  449. /**
  450. * Displays the un-applied new migrations.
  451. *
  452. * This command will show the new migrations that have not been applied.
  453. * For example,
  454. *
  455. * ```
  456. * yii migrate/new # showing the first 10 new migrations
  457. * yii migrate/new 5 # showing the first 5 new migrations
  458. * yii migrate/new all # showing all new migrations
  459. * ```
  460. *
  461. * @param int $limit the maximum number of new migrations to be displayed.
  462. * If it is `all`, all available new migrations will be displayed.
  463. * @throws \yii\console\Exception if invalid limit value passed
  464. */
  465. public function actionNew($limit = 10)
  466. {
  467. if ($limit === 'all') {
  468. $limit = null;
  469. } else {
  470. $limit = (int) $limit;
  471. if ($limit < 1) {
  472. throw new Exception('The limit must be greater than 0.');
  473. }
  474. }
  475. $migrations = $this->getNewMigrations();
  476. if (empty($migrations)) {
  477. $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
  478. } else {
  479. $n = count($migrations);
  480. if ($limit && $n > $limit) {
  481. $migrations = array_slice($migrations, 0, $limit);
  482. $this->stdout("Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
  483. } else {
  484. $this->stdout("Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
  485. }
  486. foreach ($migrations as $migration) {
  487. $this->stdout("\t" . $migration . "\n");
  488. }
  489. }
  490. }
  491. /**
  492. * Creates a new migration.
  493. *
  494. * This command creates a new migration using the available migration template.
  495. * After using this command, developers should modify the created migration
  496. * skeleton by filling up the actual migration logic.
  497. *
  498. * ```
  499. * yii migrate/create create_user_table
  500. * ```
  501. *
  502. * In order to generate a namespaced migration, you should specify a namespace before the migration's name.
  503. * Note that backslash (`\`) is usually considered a special character in the shell, so you need to escape it
  504. * properly to avoid shell errors or incorrect behavior.
  505. * For example:
  506. *
  507. * ```
  508. * yii migrate/create 'app\\migrations\\createUserTable'
  509. * ```
  510. *
  511. * In case [[migrationPath]] is not set and no namespace is provided, the first entry of [[migrationNamespaces]] will be used.
  512. *
  513. * @param string $name the name of the new migration. This should only contain
  514. * letters, digits, underscores and/or backslashes.
  515. *
  516. * Note: If the migration name is of a special form, for example create_xxx or
  517. * drop_xxx, then the generated migration file will contain extra code,
  518. * in this case for creating/dropping tables.
  519. *
  520. * @throws Exception if the name argument is invalid.
  521. */
  522. public function actionCreate($name)
  523. {
  524. if (!preg_match('/^[\w\\\\]+$/', $name)) {
  525. throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.');
  526. }
  527. list($namespace, $className) = $this->generateClassName($name);
  528. $migrationPath = $this->findMigrationPath($namespace);
  529. $file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php';
  530. if ($this->confirm("Create new migration '$file'?")) {
  531. $content = $this->generateMigrationSourceCode([
  532. 'name' => $name,
  533. 'className' => $className,
  534. 'namespace' => $namespace,
  535. ]);
  536. FileHelper::createDirectory($migrationPath);
  537. file_put_contents($file, $content);
  538. $this->stdout("New migration created successfully.\n", Console::FG_GREEN);
  539. }
  540. }
  541. /**
  542. * Generates class base name and namespace from migration name from user input.
  543. * @param string $name migration name from user input.
  544. * @return array list of 2 elements: 'namespace' and 'class base name'
  545. * @since 2.0.10
  546. */
  547. private function generateClassName($name)
  548. {
  549. $namespace = null;
  550. $name = trim($name, '\\');
  551. if (strpos($name, '\\') !== false) {
  552. $namespace = substr($name, 0, strrpos($name, '\\'));
  553. $name = substr($name, strrpos($name, '\\') + 1);
  554. } else {
  555. if ($this->migrationPath === null) {
  556. $migrationNamespaces = $this->migrationNamespaces;
  557. $namespace = array_shift($migrationNamespaces);
  558. }
  559. }
  560. if ($namespace === null) {
  561. $class = 'm' . gmdate('ymd_His') . '_' . $name;
  562. } else {
  563. $class = 'M' . gmdate('ymdHis') . ucfirst($name);
  564. }
  565. return [$namespace, $class];
  566. }
  567. /**
  568. * Finds the file path for the specified migration namespace.
  569. * @param string|null $namespace migration namespace.
  570. * @return string migration file path.
  571. * @throws Exception on failure.
  572. * @since 2.0.10
  573. */
  574. private function findMigrationPath($namespace)
  575. {
  576. if (empty($namespace)) {
  577. return is_array($this->migrationPath) ? reset($this->migrationPath) : $this->migrationPath;
  578. }
  579. if (!in_array($namespace, $this->migrationNamespaces, true)) {
  580. throw new Exception("Namespace '{$namespace}' not found in `migrationNamespaces`");
  581. }
  582. return $this->getNamespacePath($namespace);
  583. }
  584. /**
  585. * Returns the file path matching the give namespace.
  586. * @param string $namespace namespace.
  587. * @return string file path.
  588. * @since 2.0.10
  589. */
  590. private function getNamespacePath($namespace)
  591. {
  592. return str_replace('/', DIRECTORY_SEPARATOR, Yii::getAlias('@' . str_replace('\\', '/', $namespace)));
  593. }
  594. /**
  595. * Upgrades with the specified migration class.
  596. * @param string $class the migration class name
  597. * @return bool whether the migration is successful
  598. */
  599. protected function migrateUp($class)
  600. {
  601. if ($class === self::BASE_MIGRATION) {
  602. return true;
  603. }
  604. $this->stdout("*** applying $class\n", Console::FG_YELLOW);
  605. $start = microtime(true);
  606. $migration = $this->createMigration($class);
  607. if ($migration->up() !== false) {
  608. $this->addMigrationHistory($class);
  609. $time = microtime(true) - $start;
  610. $this->stdout("*** applied $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
  611. return true;
  612. } else {
  613. $time = microtime(true) - $start;
  614. $this->stdout("*** failed to apply $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
  615. return false;
  616. }
  617. }
  618. /**
  619. * Downgrades with the specified migration class.
  620. * @param string $class the migration class name
  621. * @return bool whether the migration is successful
  622. */
  623. protected function migrateDown($class)
  624. {
  625. if ($class === self::BASE_MIGRATION) {
  626. return true;
  627. }
  628. $this->stdout("*** reverting $class\n", Console::FG_YELLOW);
  629. $start = microtime(true);
  630. $migration = $this->createMigration($class);
  631. if ($migration->down() !== false) {
  632. $this->removeMigrationHistory($class);
  633. $time = microtime(true) - $start;
  634. $this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
  635. return true;
  636. } else {
  637. $time = microtime(true) - $start;
  638. $this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
  639. return false;
  640. }
  641. }
  642. /**
  643. * Creates a new migration instance.
  644. * @param string $class the migration class name
  645. * @return \yii\db\MigrationInterface the migration instance
  646. */
  647. protected function createMigration($class)
  648. {
  649. $this->includeMigrationFile($class);
  650. return new $class();
  651. }
  652. /**
  653. * Includes the migration file for a given migration class name.
  654. *
  655. * This function will do nothing on namespaced migrations, which are loaded by
  656. * autoloading automatically. It will include the migration file, by searching
  657. * [[migrationPath]] for classes without namespace.
  658. * @param string $class the migration class name.
  659. * @since 2.0.12
  660. */
  661. protected function includeMigrationFile($class)
  662. {
  663. $class = trim($class, '\\');
  664. if (strpos($class, '\\') === false) {
  665. if (is_array($this->migrationPath)) {
  666. foreach($this->migrationPath as $path) {
  667. $file = $path . DIRECTORY_SEPARATOR . $class . '.php';
  668. if (is_file($file)) {
  669. require_once($file);
  670. break;
  671. }
  672. }
  673. } else {
  674. $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
  675. require_once($file);
  676. }
  677. }
  678. }
  679. /**
  680. * Migrates to the specified apply time in the past.
  681. * @param int $time UNIX timestamp value.
  682. */
  683. protected function migrateToTime($time)
  684. {
  685. $count = 0;
  686. $migrations = array_values($this->getMigrationHistory(null));
  687. while ($count < count($migrations) && $migrations[$count] > $time) {
  688. ++$count;
  689. }
  690. if ($count === 0) {
  691. $this->stdout("Nothing needs to be done.\n", Console::FG_GREEN);
  692. } else {
  693. $this->actionDown($count);
  694. }
  695. }
  696. /**
  697. * Migrates to the certain version.
  698. * @param string $version name in the full format.
  699. * @return int CLI exit code
  700. * @throws Exception if the provided version cannot be found.
  701. */
  702. protected function migrateToVersion($version)
  703. {
  704. $originalVersion = $version;
  705. // try migrate up
  706. $migrations = $this->getNewMigrations();
  707. foreach ($migrations as $i => $migration) {
  708. if (strpos($migration, $version) === 0) {
  709. $this->actionUp($i + 1);
  710. return self::EXIT_CODE_NORMAL;
  711. }
  712. }
  713. // try migrate down
  714. $migrations = array_keys($this->getMigrationHistory(null));
  715. foreach ($migrations as $i => $migration) {
  716. if (strpos($migration, $version) === 0) {
  717. if ($i === 0) {
  718. $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
  719. } else {
  720. $this->actionDown($i);
  721. }
  722. return self::EXIT_CODE_NORMAL;
  723. }
  724. }
  725. throw new Exception("Unable to find the version '$originalVersion'.");
  726. }
  727. /**
  728. * Returns the migrations that are not applied.
  729. * @return array list of new migrations
  730. */
  731. protected function getNewMigrations()
  732. {
  733. $applied = [];
  734. foreach ($this->getMigrationHistory(null) as $class => $time) {
  735. $applied[trim($class, '\\')] = true;
  736. }
  737. $migrationPaths = [];
  738. if (is_array($this->migrationPath)) {
  739. foreach($this->migrationPath as $path) {
  740. $migrationPaths[] = [$path, ''];
  741. }
  742. } elseif (!empty($this->migrationPath)) {
  743. $migrationPaths[] = [$this->migrationPath, ''];
  744. }
  745. foreach ($this->migrationNamespaces as $namespace) {
  746. $migrationPaths[] = [$this->getNamespacePath($namespace), $namespace];
  747. }
  748. $migrations = [];
  749. foreach ($migrationPaths as $item) {
  750. list($migrationPath, $namespace) = $item;
  751. if (!file_exists($migrationPath)) {
  752. continue;
  753. }
  754. $handle = opendir($migrationPath);
  755. while (($file = readdir($handle)) !== false) {
  756. if ($file === '.' || $file === '..') {
  757. continue;
  758. }
  759. $path = $migrationPath . DIRECTORY_SEPARATOR . $file;
  760. if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) {
  761. $class = $matches[1];
  762. if (!empty($namespace)) {
  763. $class = $namespace . '\\' . $class;
  764. }
  765. $time = str_replace('_', '', $matches[2]);
  766. if (!isset($applied[$class])) {
  767. $migrations[$time . '\\' . $class] = $class;
  768. }
  769. }
  770. }
  771. closedir($handle);
  772. }
  773. ksort($migrations);
  774. return array_values($migrations);
  775. }
  776. /**
  777. * Generates new migration source PHP code.
  778. * Child class may override this method, adding extra logic or variation to the process.
  779. * @param array $params generation parameters, usually following parameters are present:
  780. *
  781. * - name: string migration base name
  782. * - className: string migration class name
  783. *
  784. * @return string generated PHP code.
  785. * @since 2.0.8
  786. */
  787. protected function generateMigrationSourceCode($params)
  788. {
  789. return $this->renderFile(Yii::getAlias($this->templateFile), $params);
  790. }
  791. /**
  792. * Returns the migration history.
  793. * @param int $limit the maximum number of records in the history to be returned. `null` for "no limit".
  794. * @return array the migration history
  795. */
  796. abstract protected function getMigrationHistory($limit);
  797. /**
  798. * Adds new migration entry to the history.
  799. * @param string $version migration version name.
  800. */
  801. abstract protected function addMigrationHistory($version);
  802. /**
  803. * Removes existing migration from the history.
  804. * @param string $version migration version name.
  805. */
  806. abstract protected function removeMigrationHistory($version);
  807. }