BaseMigrateController.php 36 KB

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