Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. $this->db->enableSlaves = false;
  67. }
  68. /**
  69. * @inheritdoc
  70. * @since 2.0.6
  71. */
  72. protected function getDb()
  73. {
  74. return $this->db;
  75. }
  76. /**
  77. * This method contains the logic to be executed when applying this migration.
  78. * Child classes may override this method to provide actual migration logic.
  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 up()
  83. {
  84. $transaction = $this->db->beginTransaction();
  85. try {
  86. if ($this->safeUp() === 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 removing this migration.
  101. * The default implementation throws an exception indicating the migration cannot be removed.
  102. * Child classes may override this method if the corresponding migrations can be removed.
  103. * @return boolean return a false value to indicate the migration fails
  104. * and should not proceed further. All other return values mean the migration succeeds.
  105. */
  106. public function down()
  107. {
  108. $transaction = $this->db->beginTransaction();
  109. try {
  110. if ($this->safeDown() === false) {
  111. $transaction->rollBack();
  112. return false;
  113. }
  114. $transaction->commit();
  115. } catch (\Exception $e) {
  116. echo 'Exception: ' . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
  117. echo $e->getTraceAsString() . "\n";
  118. $transaction->rollBack();
  119. return false;
  120. }
  121. return null;
  122. }
  123. /**
  124. * This method contains the logic to be executed when applying this migration.
  125. * This method differs from [[up()]] in that the DB logic implemented here will
  126. * be enclosed within a DB transaction.
  127. * Child classes may implement this method instead of [[up()]] if the DB logic
  128. * needs to be within a transaction.
  129. * @return boolean return a false value to indicate the migration fails
  130. * and should not proceed further. All other return values mean the migration succeeds.
  131. */
  132. public function safeUp()
  133. {
  134. }
  135. /**
  136. * This method contains the logic to be executed when removing this migration.
  137. * This method differs from [[down()]] in that the DB logic implemented here will
  138. * be enclosed within a DB transaction.
  139. * Child classes may implement this method instead of [[down()]] if the DB logic
  140. * needs to be within a transaction.
  141. * @return boolean return a false value to indicate the migration fails
  142. * and should not proceed further. All other return values mean the migration succeeds.
  143. */
  144. public function safeDown()
  145. {
  146. }
  147. /**
  148. * Executes a SQL statement.
  149. * This method executes the specified SQL statement using [[db]].
  150. * @param string $sql the SQL statement to be executed
  151. * @param array $params input parameters (name => value) for the SQL execution.
  152. * See [[Command::execute()]] for more details.
  153. */
  154. public function execute($sql, $params = [])
  155. {
  156. echo " > execute SQL: $sql ...";
  157. $time = microtime(true);
  158. $this->db->createCommand($sql)->bindValues($params)->execute();
  159. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  160. }
  161. /**
  162. * Creates and executes an INSERT SQL statement.
  163. * The method will properly escape the column names, and bind the values to be inserted.
  164. * @param string $table the table that new rows will be inserted into.
  165. * @param array $columns the column data (name => value) to be inserted into the table.
  166. */
  167. public function insert($table, $columns)
  168. {
  169. echo " > insert into $table ...";
  170. $time = microtime(true);
  171. $this->db->createCommand()->insert($table, $columns)->execute();
  172. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  173. }
  174. /**
  175. * Creates and executes an batch INSERT SQL statement.
  176. * The method will properly escape the column names, and bind the values to be inserted.
  177. * @param string $table the table that new rows will be inserted into.
  178. * @param array $columns the column names.
  179. * @param array $rows the rows to be batch inserted into the table
  180. */
  181. public function batchInsert($table, $columns, $rows)
  182. {
  183. echo " > insert into $table ...";
  184. $time = microtime(true);
  185. $this->db->createCommand()->batchInsert($table, $columns, $rows)->execute();
  186. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  187. }
  188. /**
  189. * Creates and executes an UPDATE SQL statement.
  190. * The method will properly escape the column names and bind the values to be updated.
  191. * @param string $table the table to be updated.
  192. * @param array $columns the column data (name => value) to be updated.
  193. * @param array|string $condition the conditions that will be put in the WHERE part. Please
  194. * refer to [[Query::where()]] on how to specify conditions.
  195. * @param array $params the parameters to be bound to the query.
  196. */
  197. public function update($table, $columns, $condition = '', $params = [])
  198. {
  199. echo " > update $table ...";
  200. $time = microtime(true);
  201. $this->db->createCommand()->update($table, $columns, $condition, $params)->execute();
  202. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  203. }
  204. /**
  205. * Creates and executes a DELETE SQL statement.
  206. * @param string $table the table where the data will be deleted from.
  207. * @param array|string $condition the conditions that will be put in the WHERE part. Please
  208. * refer to [[Query::where()]] on how to specify conditions.
  209. * @param array $params the parameters to be bound to the query.
  210. */
  211. public function delete($table, $condition = '', $params = [])
  212. {
  213. echo " > delete from $table ...";
  214. $time = microtime(true);
  215. $this->db->createCommand()->delete($table, $condition, $params)->execute();
  216. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  217. }
  218. /**
  219. * Builds and executes a SQL statement for creating a new DB table.
  220. *
  221. * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
  222. * where name stands for a column name which will be properly quoted by the method, and definition
  223. * stands for the column type which can contain an abstract DB type.
  224. *
  225. * The [[QueryBuilder::getColumnType()]] method will be invoked to convert any abstract type into a physical one.
  226. *
  227. * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
  228. * put into the generated SQL.
  229. *
  230. * @param string $table the name of the table to be created. The name will be properly quoted by the method.
  231. * @param array $columns the columns (name => definition) in the new table.
  232. * @param string $options additional SQL fragment that will be appended to the generated SQL.
  233. */
  234. public function createTable($table, $columns, $options = null)
  235. {
  236. echo " > create table $table ...";
  237. $time = microtime(true);
  238. $this->db->createCommand()->createTable($table, $columns, $options)->execute();
  239. foreach ($columns as $column => $type) {
  240. if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
  241. $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
  242. }
  243. }
  244. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  245. }
  246. /**
  247. * Builds and executes a SQL statement for renaming a DB table.
  248. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  249. * @param string $newName the new table name. The name will be properly quoted by the method.
  250. */
  251. public function renameTable($table, $newName)
  252. {
  253. echo " > rename table $table to $newName ...";
  254. $time = microtime(true);
  255. $this->db->createCommand()->renameTable($table, $newName)->execute();
  256. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  257. }
  258. /**
  259. * Builds and executes a SQL statement for dropping a DB table.
  260. * @param string $table the table to be dropped. The name will be properly quoted by the method.
  261. */
  262. public function dropTable($table)
  263. {
  264. echo " > drop table $table ...";
  265. $time = microtime(true);
  266. $this->db->createCommand()->dropTable($table)->execute();
  267. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  268. }
  269. /**
  270. * Builds and executes a SQL statement for truncating a DB table.
  271. * @param string $table the table to be truncated. The name will be properly quoted by the method.
  272. */
  273. public function truncateTable($table)
  274. {
  275. echo " > truncate table $table ...";
  276. $time = microtime(true);
  277. $this->db->createCommand()->truncateTable($table)->execute();
  278. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  279. }
  280. /**
  281. * Builds and executes a SQL statement for adding a new DB column.
  282. * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
  283. * @param string $column the name of the new column. The name will be properly quoted by the method.
  284. * @param string $type the column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
  285. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  286. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  287. */
  288. public function addColumn($table, $column, $type)
  289. {
  290. echo " > add column $column $type to table $table ...";
  291. $time = microtime(true);
  292. $this->db->createCommand()->addColumn($table, $column, $type)->execute();
  293. if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
  294. $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
  295. }
  296. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  297. }
  298. /**
  299. * Builds and executes a SQL statement for dropping a DB column.
  300. * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
  301. * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
  302. */
  303. public function dropColumn($table, $column)
  304. {
  305. echo " > drop column $column from table $table ...";
  306. $time = microtime(true);
  307. $this->db->createCommand()->dropColumn($table, $column)->execute();
  308. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  309. }
  310. /**
  311. * Builds and executes a SQL statement for renaming a column.
  312. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  313. * @param string $name the old name of the column. The name will be properly quoted by the method.
  314. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  315. */
  316. public function renameColumn($table, $name, $newName)
  317. {
  318. echo " > rename column $name in table $table to $newName ...";
  319. $time = microtime(true);
  320. $this->db->createCommand()->renameColumn($table, $name, $newName)->execute();
  321. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  322. }
  323. /**
  324. * Builds and executes a SQL statement for changing the definition of a column.
  325. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  326. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  327. * @param string $type the new column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
  328. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  329. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  330. */
  331. public function alterColumn($table, $column, $type)
  332. {
  333. echo " > alter column $column in table $table to $type ...";
  334. $time = microtime(true);
  335. $this->db->createCommand()->alterColumn($table, $column, $type)->execute();
  336. if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
  337. $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
  338. }
  339. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  340. }
  341. /**
  342. * Builds and executes a SQL statement for creating a primary key.
  343. * The method will properly quote the table and column names.
  344. * @param string $name the name of the primary key constraint.
  345. * @param string $table the table that the primary key constraint will be added to.
  346. * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
  347. */
  348. public function addPrimaryKey($name, $table, $columns)
  349. {
  350. echo " > add primary key $name on $table (" . (is_array($columns) ? implode(',', $columns) : $columns) . ') ...';
  351. $time = microtime(true);
  352. $this->db->createCommand()->addPrimaryKey($name, $table, $columns)->execute();
  353. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  354. }
  355. /**
  356. * Builds and executes a SQL statement for dropping a primary key.
  357. * @param string $name the name of the primary key constraint to be removed.
  358. * @param string $table the table that the primary key constraint will be removed from.
  359. */
  360. public function dropPrimaryKey($name, $table)
  361. {
  362. echo " > drop primary key $name ...";
  363. $time = microtime(true);
  364. $this->db->createCommand()->dropPrimaryKey($name, $table)->execute();
  365. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  366. }
  367. /**
  368. * Builds a SQL statement for adding a foreign key constraint to an existing table.
  369. * The method will properly quote the table and column names.
  370. * @param string $name the name of the foreign key constraint.
  371. * @param string $table the table that the foreign key constraint will be added to.
  372. * @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.
  373. * @param string $refTable the table that the foreign key references to.
  374. * @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.
  375. * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  376. * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  377. */
  378. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
  379. {
  380. echo " > add foreign key $name: $table (" . implode(',', (array) $columns) . ") references $refTable (" . implode(',', (array) $refColumns) . ') ...';
  381. $time = microtime(true);
  382. $this->db->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute();
  383. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  384. }
  385. /**
  386. * Builds a SQL statement for dropping a foreign key constraint.
  387. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  388. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  389. */
  390. public function dropForeignKey($name, $table)
  391. {
  392. echo " > drop foreign key $name from table $table ...";
  393. $time = microtime(true);
  394. $this->db->createCommand()->dropForeignKey($name, $table)->execute();
  395. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  396. }
  397. /**
  398. * Builds and executes a SQL statement for creating a new index.
  399. * @param string $name the name of the index. The name will be properly quoted by the method.
  400. * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
  401. * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
  402. * by commas or use an array. Each column name will be properly quoted by the method. Quoting will be skipped for column names that
  403. * include a left parenthesis "(".
  404. * @param boolean $unique whether to add UNIQUE constraint on the created index.
  405. */
  406. public function createIndex($name, $table, $columns, $unique = false)
  407. {
  408. echo ' > create' . ($unique ? ' unique' : '') . " index $name on $table (" . implode(',', (array) $columns) . ') ...';
  409. $time = microtime(true);
  410. $this->db->createCommand()->createIndex($name, $table, $columns, $unique)->execute();
  411. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  412. }
  413. /**
  414. * Builds and executes a SQL statement for dropping an index.
  415. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  416. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  417. */
  418. public function dropIndex($name, $table)
  419. {
  420. echo " > drop index $name on $table ...";
  421. $time = microtime(true);
  422. $this->db->createCommand()->dropIndex($name, $table)->execute();
  423. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  424. }
  425. /**
  426. * Builds and execute a SQL statement for adding comment to column
  427. *
  428. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  429. * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
  430. * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
  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. * @since 2.0.8
  446. */
  447. public function addCommentOnTable($table, $comment)
  448. {
  449. echo " > add comment on table $table ...";
  450. $time = microtime(true);
  451. $this->db->createCommand()->addCommentOnTable($table, $comment)->execute();
  452. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  453. }
  454. /**
  455. * Builds and execute a SQL statement for dropping comment from column
  456. *
  457. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  458. * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
  459. * @since 2.0.8
  460. */
  461. public function dropCommentFromColumn($table, $column)
  462. {
  463. echo " > drop comment from column $column ...";
  464. $time = microtime(true);
  465. $this->db->createCommand()->dropCommentFromColumn($table, $column)->execute();
  466. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  467. }
  468. /**
  469. * Builds a SQL statement for dropping comment from table
  470. *
  471. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  472. * @since 2.0.8
  473. */
  474. public function dropCommentFromTable($table)
  475. {
  476. echo " > drop comment from table $table ...";
  477. $time = microtime(true);
  478. $this->db->createCommand()->dropCommentFromTable($table)->execute();
  479. echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
  480. }
  481. }