BaseMigrateController.php 31 KB

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