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.

385 lines
13KB

  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. * @author Qiang Xue <qiang.xue@gmail.com>
  51. * @since 2.0
  52. */
  53. class MigrateController extends BaseMigrateController
  54. {
  55. /**
  56. * @var string the name of the table for keeping applied migration information.
  57. */
  58. public $migrationTable = '{{%migration}}';
  59. /**
  60. * @inheritdoc
  61. */
  62. public $templateFile = '@yii/views/migration.php';
  63. /**
  64. * @var array a set of template paths for generating migration code automatically.
  65. *
  66. * The key is the template type, the value is a path or the alias. Supported types are:
  67. * - `create_table`: table creating template
  68. * - `drop_table`: table dropping template
  69. * - `add_column`: adding new column template
  70. * - `drop_column`: dropping column template
  71. * - `create_junction`: create junction template
  72. *
  73. * @since 2.0.7
  74. */
  75. public $generatorTemplateFiles = [
  76. 'create_table' => '@yii/views/createTableMigration.php',
  77. 'drop_table' => '@yii/views/dropTableMigration.php',
  78. 'add_column' => '@yii/views/addColumnMigration.php',
  79. 'drop_column' => '@yii/views/dropColumnMigration.php',
  80. 'create_junction' => '@yii/views/createTableMigration.php',
  81. ];
  82. /**
  83. * @var boolean indicates whether the table names generated should consider
  84. * the `tablePrefix` setting of the DB connection. For example, if the table
  85. * name is `post` the generator wil return `{{%post}}`.
  86. * @since 2.0.8
  87. */
  88. public $useTablePrefix = false;
  89. /**
  90. * @var array column definition strings used for creating migration code.
  91. *
  92. * The format of each definition is `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. Delimiter is `,`.
  93. * For example, `--fields="name:string(12):notNull:unique"`
  94. * produces a string column of size 12 which is not null and unique values.
  95. *
  96. * Note: primary key is added automatically and is named id by default.
  97. * If you want to use another name you may specify it explicitly like
  98. * `--fields="id_key:primaryKey,name:string(12):notNull:unique"`
  99. * @since 2.0.7
  100. */
  101. public $fields = [];
  102. /**
  103. * @var Connection|array|string the DB connection object or the application component ID of the DB connection to use
  104. * when applying migrations. Starting from version 2.0.3, this can also be a configuration array
  105. * for creating the object.
  106. */
  107. public $db = 'db';
  108. /**
  109. * @inheritdoc
  110. */
  111. public function options($actionID)
  112. {
  113. return array_merge(
  114. parent::options($actionID),
  115. ['migrationTable', 'db'], // global for all actions
  116. $actionID === 'create'
  117. ? ['templateFile', 'fields', 'useTablePrefix']
  118. : []
  119. );
  120. }
  121. /**
  122. * @inheritdoc
  123. * @since 2.0.8
  124. */
  125. public function optionAliases()
  126. {
  127. return array_merge(parent::optionAliases(), [
  128. 'f' => 'fields',
  129. 'p' => 'migrationPath',
  130. 't' => 'migrationTable',
  131. 'F' => 'templateFile',
  132. 'P' => 'useTablePrefix',
  133. ]);
  134. }
  135. /**
  136. * This method is invoked right before an action is to be executed (after all possible filters.)
  137. * It checks the existence of the [[migrationPath]].
  138. * @param \yii\base\Action $action the action to be executed.
  139. * @return boolean whether the action should continue to be executed.
  140. */
  141. public function beforeAction($action)
  142. {
  143. if (parent::beforeAction($action)) {
  144. if ($action->id !== 'create') {
  145. $this->db = Instance::ensure($this->db, Connection::className());
  146. }
  147. return true;
  148. } else {
  149. return false;
  150. }
  151. }
  152. /**
  153. * Creates a new migration instance.
  154. * @param string $class the migration class name
  155. * @return \yii\db\Migration the migration instance
  156. */
  157. protected function createMigration($class)
  158. {
  159. $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
  160. require_once($file);
  161. return new $class(['db' => $this->db]);
  162. }
  163. /**
  164. * @inheritdoc
  165. */
  166. protected function getMigrationHistory($limit)
  167. {
  168. if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
  169. $this->createMigrationHistoryTable();
  170. }
  171. $query = new Query;
  172. $rows = $query->select(['version', 'apply_time'])
  173. ->from($this->migrationTable)
  174. ->orderBy('apply_time DESC, version DESC')
  175. ->limit($limit)
  176. ->createCommand($this->db)
  177. ->queryAll();
  178. $history = ArrayHelper::map($rows, 'version', 'apply_time');
  179. unset($history[self::BASE_MIGRATION]);
  180. return $history;
  181. }
  182. /**
  183. * Creates the migration history table.
  184. */
  185. protected function createMigrationHistoryTable()
  186. {
  187. $tableName = $this->db->schema->getRawTableName($this->migrationTable);
  188. $this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
  189. $this->db->createCommand()->createTable($this->migrationTable, [
  190. 'version' => 'varchar(180) NOT NULL PRIMARY KEY',
  191. 'apply_time' => 'integer',
  192. ])->execute();
  193. $this->db->createCommand()->insert($this->migrationTable, [
  194. 'version' => self::BASE_MIGRATION,
  195. 'apply_time' => time(),
  196. ])->execute();
  197. $this->stdout("Done.\n", Console::FG_GREEN);
  198. }
  199. /**
  200. * @inheritdoc
  201. */
  202. protected function addMigrationHistory($version)
  203. {
  204. $command = $this->db->createCommand();
  205. $command->insert($this->migrationTable, [
  206. 'version' => $version,
  207. 'apply_time' => time(),
  208. ])->execute();
  209. }
  210. /**
  211. * @inheritdoc
  212. */
  213. protected function removeMigrationHistory($version)
  214. {
  215. $command = $this->db->createCommand();
  216. $command->delete($this->migrationTable, [
  217. 'version' => $version,
  218. ])->execute();
  219. }
  220. /**
  221. * @inheritdoc
  222. * @since 2.0.8
  223. */
  224. protected function generateMigrationSourceCode($params)
  225. {
  226. $parsedFields = $this->parseFields();
  227. $fields = $parsedFields['fields'];
  228. $foreignKeys = $parsedFields['foreignKeys'];
  229. $name = $params['name'];
  230. $templateFile = $this->templateFile;
  231. $table = null;
  232. if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
  233. $templateFile = $this->generatorTemplateFiles['create_junction'];
  234. $firstTable = mb_strtolower($matches[1], Yii::$app->charset);
  235. $secondTable = mb_strtolower($matches[2], Yii::$app->charset);
  236. $fields = array_merge(
  237. [
  238. [
  239. 'property' => $firstTable . '_id',
  240. 'decorators' => 'integer()',
  241. ],
  242. [
  243. 'property' => $secondTable . '_id',
  244. 'decorators' => 'integer()',
  245. ],
  246. ],
  247. $fields,
  248. [
  249. [
  250. 'property' => 'PRIMARY KEY(' .
  251. $firstTable . '_id, ' .
  252. $secondTable . '_id)',
  253. ],
  254. ]
  255. );
  256. $foreignKeys[$firstTable . '_id'] = $firstTable;
  257. $foreignKeys[$secondTable . '_id'] = $secondTable;
  258. $table = $firstTable . '_' . $secondTable;
  259. } elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
  260. $templateFile = $this->generatorTemplateFiles['add_column'];
  261. $table = mb_strtolower($matches[2], Yii::$app->charset);
  262. } elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
  263. $templateFile = $this->generatorTemplateFiles['drop_column'];
  264. $table = mb_strtolower($matches[2], Yii::$app->charset);
  265. } elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
  266. $this->addDefaultPrimaryKey($fields);
  267. $templateFile = $this->generatorTemplateFiles['create_table'];
  268. $table = mb_strtolower($matches[1], Yii::$app->charset);
  269. } elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
  270. $this->addDefaultPrimaryKey($fields);
  271. $templateFile = $this->generatorTemplateFiles['drop_table'];
  272. $table = mb_strtolower($matches[1], Yii::$app->charset);
  273. }
  274. foreach ($foreignKeys as $column => $relatedTable) {
  275. $foreignKeys[$column] = [
  276. 'idx' => $this->generateTableName("idx-$table-$column"),
  277. 'fk' => $this->generateTableName("fk-$table-$column"),
  278. 'relatedTable' => $this->generateTableName($relatedTable),
  279. ];
  280. }
  281. return $this->renderFile(Yii::getAlias($templateFile), array_merge($params, [
  282. 'table' => $this->generateTableName($table),
  283. 'fields' => $fields,
  284. 'foreignKeys' => $foreignKeys,
  285. ]));
  286. }
  287. /**
  288. * If `useTablePrefix` equals true, then the table name will contain the
  289. * prefix format.
  290. *
  291. * @param string $tableName the table name to generate.
  292. * @return string
  293. * @since 2.0.8
  294. */
  295. protected function generateTableName($tableName)
  296. {
  297. if (!$this->useTablePrefix) {
  298. return $tableName;
  299. }
  300. return '{{%' . $tableName . '}}';
  301. }
  302. /**
  303. * Parse the command line migration fields
  304. * @return array parse result with following fields:
  305. *
  306. * - fields: array, parsed fields
  307. * - foreignKeys: array, detected foreign keys
  308. *
  309. * @since 2.0.7
  310. */
  311. protected function parseFields()
  312. {
  313. $fields = [];
  314. $foreignKeys = [];
  315. foreach ($this->fields as $index => $field) {
  316. $chunks = preg_split('/\s?:\s?/', $field, null);
  317. $property = array_shift($chunks);
  318. foreach ($chunks as $i => &$chunk) {
  319. if (strpos($chunk, 'foreignKey') === 0) {
  320. preg_match('/foreignKey\((\w*)\)/', $chunk, $matches);
  321. $foreignKeys[$property] = isset($matches[1])
  322. ? $matches[1]
  323. : preg_replace('/_id$/', '', $property);
  324. unset($chunks[$i]);
  325. continue;
  326. }
  327. if (!preg_match('/^(.+?)\(([^)]+)\)$/', $chunk)) {
  328. $chunk .= '()';
  329. }
  330. }
  331. $fields[] = [
  332. 'property' => $property,
  333. 'decorators' => implode('->', $chunks),
  334. ];
  335. }
  336. return [
  337. 'fields' => $fields,
  338. 'foreignKeys' => $foreignKeys,
  339. ];
  340. }
  341. /**
  342. * Adds default primary key to fields list if there's no primary key specified
  343. * @param array $fields parsed fields
  344. * @since 2.0.7
  345. */
  346. protected function addDefaultPrimaryKey(&$fields)
  347. {
  348. foreach ($fields as $field) {
  349. if ($field['decorators'] === 'primaryKey()') {
  350. return;
  351. }
  352. }
  353. array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
  354. }
  355. }