您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

525 行
24KB

  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\db;
  8. use yii\base\Component;
  9. use yii\di\Instance;
  10. /**
  11. * Migration is the base class for representing a database migration.
  12. *
  13. * Migration is designed to be used together with the "yii migrate" command.
  14. *
  15. * Each child class of Migration represents an individual database migration which
  16. * is identified by the child class name.
  17. *
  18. * Within each migration, the [[up()]] method should be overridden to contain the logic
  19. * for "upgrading" the database; while the [[down()]] method for the "downgrading"
  20. * logic. The "yii migrate" command manages all available migrations in an application.
  21. *
  22. * If the database supports transactions, you may also override [[safeUp()]] and
  23. * [[safeDown()]] so that if anything wrong happens during the upgrading or downgrading,
  24. * the whole migration can be reverted in a whole.
  25. *
  26. * Migration provides a set of convenient methods for manipulating database data and schema.
  27. * For example, the [[insert()]] method can be used to easily insert a row of data into
  28. * a database table; the [[createTable()]] method can be used to create a database table.
  29. * Compared with the same methods in [[Command]], these methods will display extra
  30. * information showing the method parameters and execution time, which may be useful when
  31. * applying migrations.
  32. *
  33. * @author Qiang Xue <qiang.xue@gmail.com>
  34. * @since 2.0
  35. */
  36. class Migration extends Component implements MigrationInterface
  37. {
  38. use SchemaBuilderTrait;
  39. /**
  40. * @var Connection|array|string the DB connection object or the application component ID of the DB connection
  41. * that this migration should work with. Starting from version 2.0.2, this can also be a configuration array
  42. * for creating the object.
  43. *
  44. * Note that when a Migration object is created by the `migrate` command, this property will be overwritten
  45. * by the command. If you do not want to use the DB connection provided by the command, you may override
  46. * the [[init()]] method like the following:
  47. *
  48. * ```php
  49. * public function init()
  50. * {
  51. * $this->db = 'db2';
  52. * parent::init();
  53. * }
  54. * ```
  55. */
  56. public $db = 'db';
  57. /**
  58. * Initializes the migration.
  59. * This method will set [[db]] to be the 'db' application component, if it is `null`.
  60. */
  61. public function init()
  62. {
  63. parent::init();
  64. $this->db = Instance::ensure($this->db, Connection::className());
  65. $this->db->getSchema()->refresh();
  66. }
  67. /**
  68. * @inheritdoc
  69. * @since 2.0.6
  70. */
  71. protected function getDb()
  72. {
  73. return $this->db;
  74. }
  75. /**
  76. * This method contains the logic to be executed when applying this migration.
  77. * Child classes may override this method to provide actual migration logic.
  78. * @return boolean return a false value to indicate the migration fails
  79. * and should not proceed further. All other return values mean the migration succeeds.
  80. */
  81. public function up()
  82. {
  83. $transaction = $this->db->beginTransaction();
  84. try {
  85. if ($this->safeUp() === false) {
  86. $transaction->rollBack();
  87. return false;
  88. }
  89. $transaction->commit();
  90. } catch (\Exception $e) {
  91. echo 'Exception: ' . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
  92. echo $e->getTraceAsString() . "\n";
  93. $transaction->rollBack();
  94. return false;
  95. }
  96. return null;
  97. }
  98. /**
  99. * This method contains the logic to be executed when removing this migration.
  100. * The default implementation throws an exception indicating the migration cannot be removed.
  101. * Child classes may override this method if the corresponding migrations can be removed.
  102. * @return boolean return a false value to indicate the migration fails
  103. * and should not proceed further. All other return values mean the migration succeeds.
  104. */
  105. public function down()
  106. {
  107. $transaction = $this->db->beginTransaction();
  108. try {
  109. if ($this->safeDown() === false) {
  110. $transaction->rollBack();
  111. return false;
  112. }
  113. $transaction->commit();
  114. } catch (\Exception $e) {
  115. echo 'Exception: ' . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
  116. echo $e->getTraceAsString() . "\n";
  117. $transaction->rollBack();
  118. return false;
  119. }
  120. return null;
  121. }
  122. /**
  123. * This method contains the logic to be executed when applying this migration.
  124. * This method differs from [[up()]] in that the DB logic implemented here will
  125. * be enclosed within a DB transaction.
  126. * Child classes may implement this method instead of [[up()]] if the DB logic
  127. * needs to be within a transaction.
  128. * @return boolean return a false value to indicate the migration fails
  129. * and should not proceed further. All other return values mean the migration succeeds.
  130. */
  131. public function safeUp()
  132. {
  133. }
  134. /**
  135. * This method contains the logic to be executed when removing this migration.
  136. * This method differs from [[down()]] in that the DB logic implemented here will
  137. * be enclosed within a DB transaction.
  138. * Child classes may implement this method instead of [[down()]] if the DB logic
  139. * needs to be within a transaction.
  140. * @return boolean return a false value to indicate the migration fails
  141. * and should not proceed further. All other return values mean the migration succeeds.
  142. */
  143. public function safeDown()
  144. {
  145. }
  146. /**
  147. * Executes a SQL statement.
  148. * This method executes the specified SQL statement using [[db]].
  149. * @param string $sql the SQL statement to be executed
  150. * @param array $params input parameters (name => value) for the SQL execution.
  151. * See [[Command::execute()]] for more details.
  152. */
  153. public function execute($sql, $params = [])
  154. {
  155. echo " > execute SQL: $sql ...";
  156. $time = microtime(true);
  157. $this->db->createCommand($sql)->bindValues($params)->execute();
  158. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  159. }
  160. /**
  161. * Creates and executes an INSERT SQL statement.
  162. * The method will properly escape the column names, and bind the values to be inserted.
  163. * @param string $table the table that new rows will be inserted into.
  164. * @param array $columns the column data (name => value) to be inserted into the table.
  165. */
  166. public function insert($table, $columns)
  167. {
  168. echo " > insert into $table ...";
  169. $time = microtime(true);
  170. $this->db->createCommand()->insert($table, $columns)->execute();
  171. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  172. }
  173. /**
  174. * Creates and executes an batch INSERT SQL statement.
  175. * The method will properly escape the column names, and bind the values to be inserted.
  176. * @param string $table the table that new rows will be inserted into.
  177. * @param array $columns the column names.
  178. * @param array $rows the rows to be batch inserted into the table
  179. */
  180. public function batchInsert($table, $columns, $rows)
  181. {
  182. echo " > insert into $table ...";
  183. $time = microtime(true);
  184. $this->db->createCommand()->batchInsert($table, $columns, $rows)->execute();
  185. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  186. }
  187. /**
  188. * Creates and executes an UPDATE SQL statement.
  189. * The method will properly escape the column names and bind the values to be updated.
  190. * @param string $table the table to be updated.
  191. * @param array $columns the column data (name => value) to be updated.
  192. * @param array|string $condition the conditions that will be put in the WHERE part. Please
  193. * refer to [[Query::where()]] on how to specify conditions.
  194. * @param array $params the parameters to be bound to the query.
  195. */
  196. public function update($table, $columns, $condition = '', $params = [])
  197. {
  198. echo " > update $table ...";
  199. $time = microtime(true);
  200. $this->db->createCommand()->update($table, $columns, $condition, $params)->execute();
  201. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  202. }
  203. /**
  204. * Creates and executes a DELETE SQL statement.
  205. * @param string $table the table where the data will be deleted from.
  206. * @param array|string $condition the conditions that will be put in the WHERE part. Please
  207. * refer to [[Query::where()]] on how to specify conditions.
  208. * @param array $params the parameters to be bound to the query.
  209. */
  210. public function delete($table, $condition = '', $params = [])
  211. {
  212. echo " > delete from $table ...";
  213. $time = microtime(true);
  214. $this->db->createCommand()->delete($table, $condition, $params)->execute();
  215. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  216. }
  217. /**
  218. * Builds and executes a SQL statement for creating a new DB table.
  219. *
  220. * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
  221. * where name stands for a column name which will be properly quoted by the method, and definition
  222. * stands for the column type which can contain an abstract DB type.
  223. *
  224. * The [[QueryBuilder::getColumnType()]] method will be invoked to convert any abstract type into a physical one.
  225. *
  226. * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
  227. * put into the generated SQL.
  228. *
  229. * @param string $table the name of the table to be created. The name will be properly quoted by the method.
  230. * @param array $columns the columns (name => definition) in the new table.
  231. * @param string $options additional SQL fragment that will be appended to the generated SQL.
  232. */
  233. public function createTable($table, $columns, $options = null)
  234. {
  235. echo " > create table $table ...";
  236. $time = microtime(true);
  237. $this->db->createCommand()->createTable($table, $columns, $options)->execute();
  238. foreach ($columns as $column => $type) {
  239. if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
  240. $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
  241. }
  242. }
  243. echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  244. }
  245. /**
  246. * Builds and executes a SQL statement for renaming a DB table.
  247. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  248. * @param string $newName the new table name. The name will be properly quoted by the method.
  249. */
  250. public function renameTable($table, $newName)
  251. {
  252. echo " > rename table $table to $newName ...";
  253. $time = microtime(true);
  254. $this->db->createCommand()->renameTable($table, $newName)->execute();
  255. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  256. }
  257. /**
  258. * Builds and executes a SQL statement for dropping a DB table.
  259. * @param string $table the table to be dropped. The name will be properly quoted by the method.
  260. */
  261. public function dropTable($table)
  262. {
  263. echo " > drop table $table ...";
  264. $time = microtime(true);
  265. $this->db->createCommand()->dropTable($table)->execute();
  266. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  267. }
  268. /**
  269. * Builds and executes a SQL statement for truncating a DB table.
  270. * @param string $table the table to be truncated. The name will be properly quoted by the method.
  271. */
  272. public function truncateTable($table)
  273. {
  274. echo " > truncate table $table ...";
  275. $time = microtime(true);
  276. $this->db->createCommand()->truncateTable($table)->execute();
  277. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  278. }
  279. /**
  280. * Builds and executes a SQL statement for adding a new DB column.
  281. * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
  282. * @param string $column the name of the new column. The name will be properly quoted by the method.
  283. * @param string $type the column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
  284. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  285. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  286. */
  287. public function addColumn($table, $column, $type)
  288. {
  289. echo " > add column $column $type to table $table ...";
  290. $time = microtime(true);
  291. $this->db->createCommand()->addColumn($table, $column, $type)->execute();
  292. if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
  293. $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
  294. }
  295. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  296. }
  297. /**
  298. * Builds and executes a SQL statement for dropping a DB column.
  299. * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
  300. * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
  301. */
  302. public function dropColumn($table, $column)
  303. {
  304. echo " > drop column $column from table $table ...";
  305. $time = microtime(true);
  306. $this->db->createCommand()->dropColumn($table, $column)->execute();
  307. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  308. }
  309. /**
  310. * Builds and executes a SQL statement for renaming a column.
  311. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  312. * @param string $name the old name of the column. The name will be properly quoted by the method.
  313. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  314. */
  315. public function renameColumn($table, $name, $newName)
  316. {
  317. echo " > rename column $name in table $table to $newName ...";
  318. $time = microtime(true);
  319. $this->db->createCommand()->renameColumn($table, $name, $newName)->execute();
  320. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  321. }
  322. /**
  323. * Builds and executes a SQL statement for changing the definition of a column.
  324. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  325. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  326. * @param string $type the new column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
  327. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  328. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  329. */
  330. public function alterColumn($table, $column, $type)
  331. {
  332. echo " > alter column $column in table $table to $type ...";
  333. $time = microtime(true);
  334. $this->db->createCommand()->alterColumn($table, $column, $type)->execute();
  335. if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
  336. $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
  337. }
  338. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  339. }
  340. /**
  341. * Builds and executes a SQL statement for creating a primary key.
  342. * The method will properly quote the table and column names.
  343. * @param string $name the name of the primary key constraint.
  344. * @param string $table the table that the primary key constraint will be added to.
  345. * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
  346. */
  347. public function addPrimaryKey($name, $table, $columns)
  348. {
  349. echo " > add primary key $name on $table (" . (is_array($columns) ? implode(',', $columns) : $columns) . ') ...';
  350. $time = microtime(true);
  351. $this->db->createCommand()->addPrimaryKey($name, $table, $columns)->execute();
  352. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  353. }
  354. /**
  355. * Builds and executes a SQL statement for dropping a primary key.
  356. * @param string $name the name of the primary key constraint to be removed.
  357. * @param string $table the table that the primary key constraint will be removed from.
  358. */
  359. public function dropPrimaryKey($name, $table)
  360. {
  361. echo " > drop primary key $name ...";
  362. $time = microtime(true);
  363. $this->db->createCommand()->dropPrimaryKey($name, $table)->execute();
  364. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  365. }
  366. /**
  367. * Builds a SQL statement for adding a foreign key constraint to an existing table.
  368. * The method will properly quote the table and column names.
  369. * @param string $name the name of the foreign key constraint.
  370. * @param string $table the table that the foreign key constraint will be added to.
  371. * @param string|array $columns the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas or use an array.
  372. * @param string $refTable the table that the foreign key references to.
  373. * @param string|array $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas or use an array.
  374. * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  375. * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  376. */
  377. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
  378. {
  379. echo " > add foreign key $name: $table (" . implode(',', (array) $columns) . ") references $refTable (" . implode(',', (array) $refColumns) . ') ...';
  380. $time = microtime(true);
  381. $this->db->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute();
  382. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  383. }
  384. /**
  385. * Builds a SQL statement for dropping a foreign key constraint.
  386. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  387. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  388. */
  389. public function dropForeignKey($name, $table)
  390. {
  391. echo " > drop foreign key $name from table $table ...";
  392. $time = microtime(true);
  393. $this->db->createCommand()->dropForeignKey($name, $table)->execute();
  394. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  395. }
  396. /**
  397. * Builds and executes a SQL statement for creating a new index.
  398. * @param string $name the name of the index. The name will be properly quoted by the method.
  399. * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
  400. * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
  401. * by commas or use an array. Each column name will be properly quoted by the method. Quoting will be skipped for column names that
  402. * include a left parenthesis "(".
  403. * @param boolean $unique whether to add UNIQUE constraint on the created index.
  404. */
  405. public function createIndex($name, $table, $columns, $unique = false)
  406. {
  407. echo ' > create' . ($unique ? ' unique' : '') . " index $name on $table (" . implode(',', (array) $columns) . ') ...';
  408. $time = microtime(true);
  409. $this->db->createCommand()->createIndex($name, $table, $columns, $unique)->execute();
  410. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  411. }
  412. /**
  413. * Builds and executes a SQL statement for dropping an index.
  414. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  415. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  416. */
  417. public function dropIndex($name, $table)
  418. {
  419. echo " > drop index $name ...";
  420. $time = microtime(true);
  421. $this->db->createCommand()->dropIndex($name, $table)->execute();
  422. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  423. }
  424. /**
  425. * Builds and execute a SQL statement for adding comment to column
  426. *
  427. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  428. * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
  429. * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
  430. * @return $this the command object itself
  431. * @since 2.0.8
  432. */
  433. public function addCommentOnColumn($table, $column, $comment)
  434. {
  435. echo " > add comment on column $column ...";
  436. $time = microtime(true);
  437. $this->db->createCommand()->addCommentOnColumn($table, $column, $comment)->execute();
  438. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  439. }
  440. /**
  441. * Builds a SQL statement for adding comment to table
  442. *
  443. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  444. * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
  445. * @return $this the command object itself
  446. * @since 2.0.8
  447. */
  448. public function addCommentOnTable($table, $comment)
  449. {
  450. echo " > add comment on table $table ...";
  451. $time = microtime(true);
  452. $this->db->createCommand()->addCommentOnTable($table, $comment)->execute();
  453. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  454. }
  455. /**
  456. * Builds and execute a SQL statement for dropping comment from column
  457. *
  458. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  459. * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
  460. * @return $this the command object itself
  461. * @since 2.0.8
  462. */
  463. public function dropCommentFromColumn($table, $column)
  464. {
  465. echo " > drop comment from column $column ...";
  466. $time = microtime(true);
  467. $this->db->createCommand()->dropCommentFromColumn($table, $column)->execute();
  468. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  469. }
  470. /**
  471. * Builds a SQL statement for dropping comment from table
  472. *
  473. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  474. * @return $this the command object itself
  475. * @since 2.0.8
  476. */
  477. public function dropCommentFromTable($table)
  478. {
  479. echo " > drop comment from table $table ...";
  480. $time = microtime(true);
  481. $this->db->createCommand()->dropCommentFromTable($table)->execute();
  482. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  483. }
  484. }