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