You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MigrateController.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 boolean 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 boolean 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. $rows = $query->select(['version', 'apply_time'])
  194. ->from($this->migrationTable)
  195. ->orderBy('apply_time DESC, version DESC')
  196. ->limit($limit)
  197. ->createCommand($this->db)
  198. ->queryAll();
  199. $history = ArrayHelper::map($rows, 'version', 'apply_time');
  200. unset($history[self::BASE_MIGRATION]);
  201. return $history;
  202. }
  203. /**
  204. * Creates the migration history table.
  205. */
  206. protected function createMigrationHistoryTable()
  207. {
  208. $tableName = $this->db->schema->getRawTableName($this->migrationTable);
  209. $this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
  210. $this->db->createCommand()->createTable($this->migrationTable, [
  211. 'version' => 'varchar(180) NOT NULL PRIMARY KEY',
  212. 'apply_time' => 'integer',
  213. ])->execute();
  214. $this->db->createCommand()->insert($this->migrationTable, [
  215. 'version' => self::BASE_MIGRATION,
  216. 'apply_time' => time(),
  217. ])->execute();
  218. $this->stdout("Done.\n", Console::FG_GREEN);
  219. }
  220. /**
  221. * @inheritdoc
  222. */
  223. protected function addMigrationHistory($version)
  224. {
  225. $command = $this->db->createCommand();
  226. $command->insert($this->migrationTable, [
  227. 'version' => $version,
  228. 'apply_time' => time(),
  229. ])->execute();
  230. }
  231. /**
  232. * @inheritdoc
  233. */
  234. protected function removeMigrationHistory($version)
  235. {
  236. $command = $this->db->createCommand();
  237. $command->delete($this->migrationTable, [
  238. 'version' => $version,
  239. ])->execute();
  240. }
  241. /**
  242. * @inheritdoc
  243. * @since 2.0.8
  244. */
  245. protected function generateMigrationSourceCode($params)
  246. {
  247. $parsedFields = $this->parseFields();
  248. $fields = $parsedFields['fields'];
  249. $foreignKeys = $parsedFields['foreignKeys'];
  250. $name = $params['name'];
  251. $templateFile = $this->templateFile;
  252. $table = null;
  253. if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
  254. $templateFile = $this->generatorTemplateFiles['create_junction'];
  255. $firstTable = mb_strtolower($matches[1], Yii::$app->charset);
  256. $secondTable = mb_strtolower($matches[2], Yii::$app->charset);
  257. $fields = array_merge(
  258. [
  259. [
  260. 'property' => $firstTable . '_id',
  261. 'decorators' => 'integer()',
  262. ],
  263. [
  264. 'property' => $secondTable . '_id',
  265. 'decorators' => 'integer()',
  266. ],
  267. ],
  268. $fields,
  269. [
  270. [
  271. 'property' => 'PRIMARY KEY(' .
  272. $firstTable . '_id, ' .
  273. $secondTable . '_id)',
  274. ],
  275. ]
  276. );
  277. $foreignKeys[$firstTable . '_id'] = $firstTable;
  278. $foreignKeys[$secondTable . '_id'] = $secondTable;
  279. $table = $firstTable . '_' . $secondTable;
  280. } elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
  281. $templateFile = $this->generatorTemplateFiles['add_column'];
  282. $table = mb_strtolower($matches[2], Yii::$app->charset);
  283. } elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
  284. $templateFile = $this->generatorTemplateFiles['drop_column'];
  285. $table = mb_strtolower($matches[2], Yii::$app->charset);
  286. } elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
  287. $this->addDefaultPrimaryKey($fields);
  288. $templateFile = $this->generatorTemplateFiles['create_table'];
  289. $table = mb_strtolower($matches[1], Yii::$app->charset);
  290. } elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
  291. $this->addDefaultPrimaryKey($fields);
  292. $templateFile = $this->generatorTemplateFiles['drop_table'];
  293. $table = mb_strtolower($matches[1], Yii::$app->charset);
  294. }
  295. foreach ($foreignKeys as $column => $relatedTable) {
  296. $foreignKeys[$column] = [
  297. 'idx' => $this->generateTableName("idx-$table-$column"),
  298. 'fk' => $this->generateTableName("fk-$table-$column"),
  299. 'relatedTable' => $this->generateTableName($relatedTable),
  300. ];
  301. }
  302. return $this->renderFile(Yii::getAlias($templateFile), array_merge($params, [
  303. 'table' => $this->generateTableName($table),
  304. 'fields' => $fields,
  305. 'foreignKeys' => $foreignKeys,
  306. ]));
  307. }
  308. /**
  309. * If `useTablePrefix` equals true, then the table name will contain the
  310. * prefix format.
  311. *
  312. * @param string $tableName the table name to generate.
  313. * @return string
  314. * @since 2.0.8
  315. */
  316. protected function generateTableName($tableName)
  317. {
  318. if (!$this->useTablePrefix) {
  319. return $tableName;
  320. }
  321. return '{{%' . $tableName . '}}';
  322. }
  323. /**
  324. * Parse the command line migration fields
  325. * @return array parse result with following fields:
  326. *
  327. * - fields: array, parsed fields
  328. * - foreignKeys: array, detected foreign keys
  329. *
  330. * @since 2.0.7
  331. */
  332. protected function parseFields()
  333. {
  334. $fields = [];
  335. $foreignKeys = [];
  336. foreach ($this->fields as $index => $field) {
  337. $chunks = preg_split('/\s?:\s?/', $field, null);
  338. $property = array_shift($chunks);
  339. foreach ($chunks as $i => &$chunk) {
  340. if (strpos($chunk, 'foreignKey') === 0) {
  341. preg_match('/foreignKey\((\w*)\)/', $chunk, $matches);
  342. $foreignKeys[$property] = isset($matches[1])
  343. ? $matches[1]
  344. : preg_replace('/_id$/', '', $property);
  345. unset($chunks[$i]);
  346. continue;
  347. }
  348. if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
  349. $chunk .= '()';
  350. }
  351. }
  352. $fields[] = [
  353. 'property' => $property,
  354. 'decorators' => implode('->', $chunks),
  355. ];
  356. }
  357. return [
  358. 'fields' => $fields,
  359. 'foreignKeys' => $foreignKeys,
  360. ];
  361. }
  362. /**
  363. * Adds default primary key to fields list if there's no primary key specified
  364. * @param array $fields parsed fields
  365. * @since 2.0.7
  366. */
  367. protected function addDefaultPrimaryKey(&$fields)
  368. {
  369. foreach ($fields as $field) {
  370. if ($field['decorators'] === 'primaryKey()' || $field['decorators'] === 'bigPrimaryKey()') {
  371. return;
  372. }
  373. }
  374. array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
  375. }
  376. }