MigrateController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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\db\Connection;
  10. use yii\db\Query;
  11. use yii\di\Instance;
  12. use yii\helpers\ArrayHelper;
  13. use yii\helpers\Console;
  14. /**
  15. * Manages application migrations.
  16. *
  17. * A migration means a set of persistent changes to the application environment
  18. * that is shared among different developers. For example, in an application
  19. * backed by a database, a migration may refer to a set of changes to
  20. * the database, such as creating a new table, adding a new table column.
  21. *
  22. * This command provides support for tracking the migration history, upgrading
  23. * or downloading with migrations, and creating new migration skeletons.
  24. *
  25. * The migration history is stored in a database table named
  26. * as [[migrationTable]]. The table will be automatically created the first time
  27. * this command is executed, if it does not exist. You may also manually
  28. * create it as follows:
  29. *
  30. * ```sql
  31. * CREATE TABLE migration (
  32. * version varchar(180) PRIMARY KEY,
  33. * apply_time integer
  34. * )
  35. * ```
  36. *
  37. * Below are some common usages of this command:
  38. *
  39. * ```
  40. * # creates a new migration named 'create_user_table'
  41. * yii migrate/create create_user_table
  42. *
  43. * # applies ALL new migrations
  44. * yii migrate
  45. *
  46. * # reverts the last applied migration
  47. * yii migrate/down
  48. * ```
  49. *
  50. * Since 2.0.10 you can use namespaced migrations. In order to enable this feature you should configure [[migrationNamespaces]]
  51. * property for the controller at application configuration:
  52. *
  53. * ```php
  54. * return [
  55. * 'controllerMap' => [
  56. * 'migrate' => [
  57. * 'class' => 'yii\console\controllers\MigrateController',
  58. * 'migrationNamespaces' => [
  59. * 'app\migrations',
  60. * 'some\extension\migrations',
  61. * ],
  62. * //'migrationPath' => null, // allows to disable not namespaced migration completely
  63. * ],
  64. * ],
  65. * ];
  66. * ```
  67. *
  68. * @author Qiang Xue <qiang.xue@gmail.com>
  69. * @since 2.0
  70. */
  71. class MigrateController extends BaseMigrateController
  72. {
  73. /**
  74. * @var string the name of the table for keeping applied migration information.
  75. */
  76. public $migrationTable = '{{%migration}}';
  77. /**
  78. * @inheritdoc
  79. */
  80. public $templateFile = '@yii/views/migration.php';
  81. /**
  82. * @var array a set of template paths for generating migration code automatically.
  83. *
  84. * The key is the template type, the value is a path or the alias. Supported types are:
  85. * - `create_table`: table creating template
  86. * - `drop_table`: table dropping template
  87. * - `add_column`: adding new column template
  88. * - `drop_column`: dropping column template
  89. * - `create_junction`: create junction template
  90. *
  91. * @since 2.0.7
  92. */
  93. public $generatorTemplateFiles = [
  94. 'create_table' => '@yii/views/createTableMigration.php',
  95. 'drop_table' => '@yii/views/dropTableMigration.php',
  96. 'add_column' => '@yii/views/addColumnMigration.php',
  97. 'drop_column' => '@yii/views/dropColumnMigration.php',
  98. 'create_junction' => '@yii/views/createTableMigration.php',
  99. ];
  100. /**
  101. * @var bool indicates whether the table names generated should consider
  102. * the `tablePrefix` setting of the DB connection. For example, if the table
  103. * name is `post` the generator wil return `{{%post}}`.
  104. * @since 2.0.8
  105. */
  106. public $useTablePrefix = false;
  107. /**
  108. * @var array column definition strings used for creating migration code.
  109. *
  110. * The format of each definition is `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. Delimiter is `,`.
  111. * For example, `--fields="name:string(12):notNull:unique"`
  112. * produces a string column of size 12 which is not null and unique values.
  113. *
  114. * Note: primary key is added automatically and is named id by default.
  115. * If you want to use another name you may specify it explicitly like
  116. * `--fields="id_key:primaryKey,name:string(12):notNull:unique"`
  117. * @since 2.0.7
  118. */
  119. public $fields = [];
  120. /**
  121. * @var Connection|array|string the DB connection object or the application component ID of the DB connection to use
  122. * when applying migrations. Starting from version 2.0.3, this can also be a configuration array
  123. * for creating the object.
  124. */
  125. public $db = 'db';
  126. /**
  127. * @inheritdoc
  128. */
  129. public function options($actionID)
  130. {
  131. return array_merge(
  132. parent::options($actionID),
  133. ['migrationTable', 'db'], // global for all actions
  134. $actionID === 'create'
  135. ? ['templateFile', 'fields', 'useTablePrefix']
  136. : []
  137. );
  138. }
  139. /**
  140. * @inheritdoc
  141. * @since 2.0.8
  142. */
  143. public function optionAliases()
  144. {
  145. return array_merge(parent::optionAliases(), [
  146. 'f' => 'fields',
  147. 'p' => 'migrationPath',
  148. 't' => 'migrationTable',
  149. 'F' => 'templateFile',
  150. 'P' => 'useTablePrefix',
  151. ]);
  152. }
  153. /**
  154. * This method is invoked right before an action is to be executed (after all possible filters.)
  155. * It checks the existence of the [[migrationPath]].
  156. * @param \yii\base\Action $action the action to be executed.
  157. * @return bool whether the action should continue to be executed.
  158. */
  159. public function beforeAction($action)
  160. {
  161. if (parent::beforeAction($action)) {
  162. if ($action->id !== 'create') {
  163. $this->db = Instance::ensure($this->db, Connection::className());
  164. }
  165. return true;
  166. } else {
  167. return false;
  168. }
  169. }
  170. /**
  171. * Creates a new migration instance.
  172. * @param string $class the migration class name
  173. * @return \yii\db\Migration the migration instance
  174. */
  175. protected function createMigration($class)
  176. {
  177. $this->includeMigrationFile($class);
  178. return new $class(['db' => $this->db]);
  179. }
  180. /**
  181. * @inheritdoc
  182. */
  183. protected function getMigrationHistory($limit)
  184. {
  185. if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
  186. $this->createMigrationHistoryTable();
  187. }
  188. $query = (new Query())
  189. ->select(['version', 'apply_time'])
  190. ->from($this->migrationTable)
  191. ->orderBy(['apply_time' => SORT_DESC, 'version' => SORT_DESC]);
  192. if (empty($this->migrationNamespaces)) {
  193. $query->limit($limit);
  194. $rows = $query->all($this->db);
  195. $history = ArrayHelper::map($rows, 'version', 'apply_time');
  196. unset($history[self::BASE_MIGRATION]);
  197. return $history;
  198. }
  199. $rows = $query->all($this->db);
  200. $history = [];
  201. foreach ($rows as $key => $row) {
  202. if ($row['version'] === self::BASE_MIGRATION) {
  203. continue;
  204. }
  205. if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?$/is', $row['version'], $matches)) {
  206. $time = str_replace('_', '', $matches[1]);
  207. $row['canonicalVersion'] = $time;
  208. } else {
  209. $row['canonicalVersion'] = $row['version'];
  210. }
  211. $row['apply_time'] = (int)$row['apply_time'];
  212. $history[] = $row;
  213. }
  214. usort($history, function ($a, $b) {
  215. if ($a['apply_time'] === $b['apply_time']) {
  216. if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) {
  217. return $compareResult;
  218. }
  219. return strcasecmp($b['version'], $a['version']);
  220. }
  221. return ($a['apply_time'] > $b['apply_time']) ? -1 : +1;
  222. });
  223. $history = array_slice($history, 0, $limit);
  224. $history = ArrayHelper::map($history, 'version', 'apply_time');
  225. return $history;
  226. }
  227. /**
  228. * Creates the migration history table.
  229. */
  230. protected function createMigrationHistoryTable()
  231. {
  232. $tableName = $this->db->schema->getRawTableName($this->migrationTable);
  233. $this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
  234. $this->db->createCommand()->createTable($this->migrationTable, [
  235. 'version' => 'varchar(180) NOT NULL PRIMARY KEY',
  236. 'apply_time' => 'integer',
  237. ])->execute();
  238. $this->db->createCommand()->insert($this->migrationTable, [
  239. 'version' => self::BASE_MIGRATION,
  240. 'apply_time' => time(),
  241. ])->execute();
  242. $this->stdout("Done.\n", Console::FG_GREEN);
  243. }
  244. /**
  245. * @inheritdoc
  246. */
  247. protected function addMigrationHistory($version)
  248. {
  249. $command = $this->db->createCommand();
  250. $command->insert($this->migrationTable, [
  251. 'version' => $version,
  252. 'apply_time' => time(),
  253. ])->execute();
  254. }
  255. /**
  256. * @inheritdoc
  257. */
  258. protected function removeMigrationHistory($version)
  259. {
  260. $command = $this->db->createCommand();
  261. $command->delete($this->migrationTable, [
  262. 'version' => $version,
  263. ])->execute();
  264. }
  265. /**
  266. * @inheritdoc
  267. * @since 2.0.8
  268. */
  269. protected function generateMigrationSourceCode($params)
  270. {
  271. $parsedFields = $this->parseFields();
  272. $fields = $parsedFields['fields'];
  273. $foreignKeys = $parsedFields['foreignKeys'];
  274. $name = $params['name'];
  275. $templateFile = $this->templateFile;
  276. $table = null;
  277. if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
  278. $templateFile = $this->generatorTemplateFiles['create_junction'];
  279. $firstTable = $matches[1];
  280. $secondTable = $matches[2];
  281. $fields = array_merge(
  282. [
  283. [
  284. 'property' => $firstTable . '_id',
  285. 'decorators' => 'integer()',
  286. ],
  287. [
  288. 'property' => $secondTable . '_id',
  289. 'decorators' => 'integer()',
  290. ],
  291. ],
  292. $fields,
  293. [
  294. [
  295. 'property' => 'PRIMARY KEY(' .
  296. $firstTable . '_id, ' .
  297. $secondTable . '_id)',
  298. ],
  299. ]
  300. );
  301. $foreignKeys[$firstTable . '_id']['table'] = $firstTable;
  302. $foreignKeys[$secondTable . '_id']['table'] = $secondTable;
  303. $foreignKeys[$firstTable . '_id']['column'] = null;
  304. $foreignKeys[$secondTable . '_id']['column'] = null;
  305. $table = $firstTable . '_' . $secondTable;
  306. } elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
  307. $templateFile = $this->generatorTemplateFiles['add_column'];
  308. $table = $matches[2];
  309. } elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
  310. $templateFile = $this->generatorTemplateFiles['drop_column'];
  311. $table = $matches[2];
  312. } elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
  313. $this->addDefaultPrimaryKey($fields);
  314. $templateFile = $this->generatorTemplateFiles['create_table'];
  315. $table = $matches[1];
  316. } elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
  317. $this->addDefaultPrimaryKey($fields);
  318. $templateFile = $this->generatorTemplateFiles['drop_table'];
  319. $table = $matches[1];
  320. }
  321. foreach ($foreignKeys as $column => $foreignKey) {
  322. $relatedColumn = $foreignKey['column'];
  323. $relatedTable = $foreignKey['table'];
  324. // Since 2.0.11 if related column name is not specified,
  325. // we're trying to get it from table schema
  326. // @see https://github.com/yiisoft/yii2/issues/12748
  327. if ($relatedColumn === null) {
  328. $relatedColumn = 'id';
  329. try {
  330. $this->db = Instance::ensure($this->db, Connection::className());
  331. $relatedTableSchema = $this->db->getTableSchema($relatedTable);
  332. if ($relatedTableSchema !== null) {
  333. $primaryKeyCount = count($relatedTableSchema->primaryKey);
  334. if ($primaryKeyCount === 1) {
  335. $relatedColumn = $relatedTableSchema->primaryKey[0];
  336. } elseif ($primaryKeyCount > 1) {
  337. $this->stdout("Related table for field \"{$column}\" exists, but primary key is composite. Default name \"id\" will be used for related field\n", Console::FG_YELLOW);
  338. } elseif ($primaryKeyCount === 0) {
  339. $this->stdout("Related table for field \"{$column}\" exists, but does not have a primary key. Default name \"id\" will be used for related field.\n", Console::FG_YELLOW);
  340. }
  341. }
  342. } catch (\ReflectionException $e) {
  343. $this->stdout("Cannot initialize database component to try reading referenced table schema for field \"{$column}\". Default name \"id\" will be used for related field.\n", Console::FG_YELLOW);
  344. }
  345. }
  346. $foreignKeys[$column] = [
  347. 'idx' => $this->generateTableName("idx-$table-$column"),
  348. 'fk' => $this->generateTableName("fk-$table-$column"),
  349. 'relatedTable' => $this->generateTableName($relatedTable),
  350. 'relatedColumn' => $relatedColumn,
  351. ];
  352. }
  353. return $this->renderFile(Yii::getAlias($templateFile), array_merge($params, [
  354. 'table' => $this->generateTableName($table),
  355. 'fields' => $fields,
  356. 'foreignKeys' => $foreignKeys,
  357. ]));
  358. }
  359. /**
  360. * If `useTablePrefix` equals true, then the table name will contain the
  361. * prefix format.
  362. *
  363. * @param string $tableName the table name to generate.
  364. * @return string
  365. * @since 2.0.8
  366. */
  367. protected function generateTableName($tableName)
  368. {
  369. if (!$this->useTablePrefix) {
  370. return $tableName;
  371. }
  372. return '{{%' . $tableName . '}}';
  373. }
  374. /**
  375. * Parse the command line migration fields
  376. * @return array parse result with following fields:
  377. *
  378. * - fields: array, parsed fields
  379. * - foreignKeys: array, detected foreign keys
  380. *
  381. * @since 2.0.7
  382. */
  383. protected function parseFields()
  384. {
  385. $fields = [];
  386. $foreignKeys = [];
  387. foreach ($this->fields as $index => $field) {
  388. $chunks = preg_split('/\s?:\s?/', $field, null);
  389. $property = array_shift($chunks);
  390. foreach ($chunks as $i => &$chunk) {
  391. if (strpos($chunk, 'foreignKey') === 0) {
  392. preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
  393. $foreignKeys[$property] = [
  394. 'table' => isset($matches[1])
  395. ? $matches[1]
  396. : preg_replace('/_id$/', '', $property),
  397. 'column' => !empty($matches[2])
  398. ? $matches[2]
  399. : null,
  400. ];
  401. unset($chunks[$i]);
  402. continue;
  403. }
  404. if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
  405. $chunk .= '()';
  406. }
  407. }
  408. $fields[] = [
  409. 'property' => $property,
  410. 'decorators' => implode('->', $chunks),
  411. ];
  412. }
  413. return [
  414. 'fields' => $fields,
  415. 'foreignKeys' => $foreignKeys,
  416. ];
  417. }
  418. /**
  419. * Adds default primary key to fields list if there's no primary key specified
  420. * @param array $fields parsed fields
  421. * @since 2.0.7
  422. */
  423. protected function addDefaultPrimaryKey(&$fields)
  424. {
  425. foreach ($fields as $field) {
  426. if (false !== strripos($field['decorators'], 'primarykey()')) {
  427. return;
  428. }
  429. }
  430. array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
  431. }
  432. }