Migration.php 18 KB

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