MigrateController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. $class = trim($class, '\\');
  178. if (strpos($class, '\\') === false) {
  179. $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
  180. require_once($file);
  181. }
  182. return new $class(['db' => $this->db]);
  183. }
  184. /**
  185. * @inheritdoc
  186. */
  187. protected function getMigrationHistory($limit)
  188. {
  189. if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
  190. $this->createMigrationHistoryTable();
  191. }
  192. $query = (new Query())
  193. ->select(['version', 'apply_time'])
  194. ->from($this->migrationTable)
  195. ->orderBy(['apply_time' => SORT_DESC, 'version' => SORT_DESC]);
  196. if (empty($this->migrationNamespaces)) {
  197. $query->limit($limit);
  198. $rows = $query->all($this->db);
  199. $history = ArrayHelper::map($rows, 'version', 'apply_time');
  200. unset($history[self::BASE_MIGRATION]);
  201. return $history;
  202. }
  203. $rows = $query->all($this->db);
  204. $history = [];
  205. foreach ($rows as $key => $row) {
  206. if ($row['version'] === self::BASE_MIGRATION) {
  207. continue;
  208. }
  209. if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?$/is', $row['version'], $matches)) {
  210. $time = str_replace('_', '', $matches[1]);
  211. $row['canonicalVersion'] = $time;
  212. } else {
  213. $row['canonicalVersion'] = $row['version'];
  214. }
  215. $row['apply_time'] = (int)$row['apply_time'];
  216. $history[] = $row;
  217. }
  218. usort($history, function ($a, $b) {
  219. if ($a['apply_time'] === $b['apply_time']) {
  220. if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) {
  221. return $compareResult;
  222. }
  223. return strcasecmp($b['version'], $a['version']);
  224. }
  225. return ($a['apply_time'] > $b['apply_time']) ? -1 : +1;
  226. });
  227. $history = array_slice($history, 0, $limit);
  228. $history = ArrayHelper::map($history, 'version', 'apply_time');
  229. return $history;
  230. }
  231. /**
  232. * Creates the migration history table.
  233. */
  234. protected function createMigrationHistoryTable()
  235. {
  236. $tableName = $this->db->schema->getRawTableName($this->migrationTable);
  237. $this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
  238. $this->db->createCommand()->createTable($this->migrationTable, [
  239. 'version' => 'varchar(180) NOT NULL PRIMARY KEY',
  240. 'apply_time' => 'integer',
  241. ])->execute();
  242. $this->db->createCommand()->insert($this->migrationTable, [
  243. 'version' => self::BASE_MIGRATION,
  244. 'apply_time' => time(),
  245. ])->execute();
  246. $this->stdout("Done.\n", Console::FG_GREEN);
  247. }
  248. /**
  249. * @inheritdoc
  250. */
  251. protected function addMigrationHistory($version)
  252. {
  253. $command = $this->db->createCommand();
  254. $command->insert($this->migrationTable, [
  255. 'version' => $version,
  256. 'apply_time' => time(),
  257. ])->execute();
  258. }
  259. /**
  260. * @inheritdoc
  261. */
  262. protected function removeMigrationHistory($version)
  263. {
  264. $command = $this->db->createCommand();
  265. $command->delete($this->migrationTable, [
  266. 'version' => $version,
  267. ])->execute();
  268. }
  269. /**
  270. * @inheritdoc
  271. * @since 2.0.8
  272. */
  273. protected function generateMigrationSourceCode($params)
  274. {
  275. $parsedFields = $this->parseFields();
  276. $fields = $parsedFields['fields'];
  277. $foreignKeys = $parsedFields['foreignKeys'];
  278. $name = $params['name'];
  279. $templateFile = $this->templateFile;
  280. $table = null;
  281. if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
  282. $templateFile = $this->generatorTemplateFiles['create_junction'];
  283. $firstTable = $matches[1];
  284. $secondTable = $matches[2];
  285. $fields = array_merge(
  286. [
  287. [
  288. 'property' => $firstTable . '_id',
  289. 'decorators' => 'integer()',
  290. ],
  291. [
  292. 'property' => $secondTable . '_id',
  293. 'decorators' => 'integer()',
  294. ],
  295. ],
  296. $fields,
  297. [
  298. [
  299. 'property' => 'PRIMARY KEY(' .
  300. $firstTable . '_id, ' .
  301. $secondTable . '_id)',
  302. ],
  303. ]
  304. );
  305. $foreignKeys[$firstTable . '_id']['table'] = $firstTable;
  306. $foreignKeys[$secondTable . '_id']['table'] = $secondTable;
  307. $foreignKeys[$firstTable . '_id']['column'] = null;
  308. $foreignKeys[$secondTable . '_id']['column'] = null;
  309. $table = $firstTable . '_' . $secondTable;
  310. } elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
  311. $templateFile = $this->generatorTemplateFiles['add_column'];
  312. $table = $matches[2];
  313. } elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
  314. $templateFile = $this->generatorTemplateFiles['drop_column'];
  315. $table = $matches[2];
  316. } elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
  317. $this->addDefaultPrimaryKey($fields);
  318. $templateFile = $this->generatorTemplateFiles['create_table'];
  319. $table = $matches[1];
  320. } elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
  321. $this->addDefaultPrimaryKey($fields);
  322. $templateFile = $this->generatorTemplateFiles['drop_table'];
  323. $table = $matches[1];
  324. }
  325. foreach ($foreignKeys as $column => $foreignKey) {
  326. $relatedColumn = $foreignKey['column'];
  327. $relatedTable = $foreignKey['table'];
  328. // Since 2.0.11 if related column name is not specified,
  329. // we're trying to get it from table schema
  330. // @see https://github.com/yiisoft/yii2/issues/12748
  331. if ($relatedColumn === null) {
  332. $relatedColumn = 'id';
  333. try {
  334. $this->db = Instance::ensure($this->db, Connection::className());
  335. $relatedTableSchema = $this->db->getTableSchema($relatedTable);
  336. if ($relatedTableSchema !== null) {
  337. $primaryKeyCount = count($relatedTableSchema->primaryKey);
  338. if ($primaryKeyCount === 1) {
  339. $relatedColumn = $relatedTableSchema->primaryKey[0];
  340. } elseif ($primaryKeyCount > 1) {
  341. $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);
  342. } elseif ($primaryKeyCount === 0) {
  343. $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);
  344. }
  345. }
  346. } catch (\ReflectionException $e) {
  347. $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);
  348. }
  349. }
  350. $foreignKeys[$column] = [
  351. 'idx' => $this->generateTableName("idx-$table-$column"),
  352. 'fk' => $this->generateTableName("fk-$table-$column"),
  353. 'relatedTable' => $this->generateTableName($relatedTable),
  354. 'relatedColumn' => $relatedColumn,
  355. ];
  356. }
  357. return $this->renderFile(Yii::getAlias($templateFile), array_merge($params, [
  358. 'table' => $this->generateTableName($table),
  359. 'fields' => $fields,
  360. 'foreignKeys' => $foreignKeys,
  361. ]));
  362. }
  363. /**
  364. * If `useTablePrefix` equals true, then the table name will contain the
  365. * prefix format.
  366. *
  367. * @param string $tableName the table name to generate.
  368. * @return string
  369. * @since 2.0.8
  370. */
  371. protected function generateTableName($tableName)
  372. {
  373. if (!$this->useTablePrefix) {
  374. return $tableName;
  375. }
  376. return '{{%' . $tableName . '}}';
  377. }
  378. /**
  379. * Parse the command line migration fields
  380. * @return array parse result with following fields:
  381. *
  382. * - fields: array, parsed fields
  383. * - foreignKeys: array, detected foreign keys
  384. *
  385. * @since 2.0.7
  386. */
  387. protected function parseFields()
  388. {
  389. $fields = [];
  390. $foreignKeys = [];
  391. foreach ($this->fields as $index => $field) {
  392. $chunks = preg_split('/\s?:\s?/', $field, null);
  393. $property = array_shift($chunks);
  394. foreach ($chunks as $i => &$chunk) {
  395. if (strpos($chunk, 'foreignKey') === 0) {
  396. preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
  397. $foreignKeys[$property] = [
  398. 'table' => isset($matches[1])
  399. ? $matches[1]
  400. : preg_replace('/_id$/', '', $property),
  401. 'column' => !empty($matches[2])
  402. ? $matches[2]
  403. : null,
  404. ];
  405. unset($chunks[$i]);
  406. continue;
  407. }
  408. if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
  409. $chunk .= '()';
  410. }
  411. }
  412. $fields[] = [
  413. 'property' => $property,
  414. 'decorators' => implode('->', $chunks),
  415. ];
  416. }
  417. return [
  418. 'fields' => $fields,
  419. 'foreignKeys' => $foreignKeys,
  420. ];
  421. }
  422. /**
  423. * Adds default primary key to fields list if there's no primary key specified
  424. * @param array $fields parsed fields
  425. * @since 2.0.7
  426. */
  427. protected function addDefaultPrimaryKey(&$fields)
  428. {
  429. foreach ($fields as $field) {
  430. if (false !== strripos($field['decorators'], 'primarykey()')) {
  431. return;
  432. }
  433. }
  434. array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
  435. }
  436. }