1: <?php
2: /**
3: * CDbMigration class file.
4: *
5: * @author Qiang Xue <qiang.xue@gmail.com>
6: * @link http://www.yiiframework.com/
7: * @copyright 2008-2013 Yii Software LLC
8: * @license http://www.yiiframework.com/license/
9: */
10:
11: /**
12: * CDbMigration is the base class for representing a database migration.
13: *
14: * CDbMigration is designed to be used together with the "yiic migrate" command.
15: *
16: * Each child class of CDbMigration represents an individual database migration which
17: * is identified by the child class name.
18: *
19: * Within each migration, the {@link up} method contains the logic for "upgrading"
20: * the database used in an application; while the {@link down} method contains "downgrading"
21: * logic. The "yiic migrate" command manages all available migrations in an application.
22: *
23: * By overriding {@link safeUp} or {@link safeDown} methods instead of {@link up} and {@link down}
24: * the migration logic will be wrapped with a DB transaction.
25: *
26: * CDbMigration provides a set of convenient methods for manipulating database data and schema.
27: * For example, the {@link insert} method can be used to easily insert a row of data into
28: * a database table; the {@link createTable} method can be used to create a database table.
29: * Compared with the same methods in {@link CDbCommand}, these methods will display extra
30: * information showing the method parameters and execution time, which may be useful when
31: * applying migrations.
32: *
33: * @property CDbConnection $dbConnection The currently active database connection.
34: *
35: * @author Qiang Xue <qiang.xue@gmail.com>
36: * @package system.db
37: * @since 1.1.6
38: */
39: abstract class CDbMigration extends CComponent
40: {
41: private $_db;
42:
43: /**
44: * This method contains the logic to be executed when applying this migration.
45: * Child classes may implement this method to provide actual migration logic.
46: * @return boolean Returning false means, the migration will not be applied.
47: */
48: public function up()
49: {
50: $transaction=$this->getDbConnection()->beginTransaction();
51: try
52: {
53: if($this->safeUp()===false)
54: {
55: $transaction->rollback();
56: return false;
57: }
58: $transaction->commit();
59: }
60: catch(Exception $e)
61: {
62: echo "Exception: ".$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
63: echo $e->getTraceAsString()."\n";
64: $transaction->rollback();
65: return false;
66: }
67: }
68:
69: /**
70: * This method contains the logic to be executed when removing this migration.
71: * Child classes may override this method if the corresponding migrations can be removed.
72: * @return boolean Returning false means, the migration will not be applied.
73: */
74: public function down()
75: {
76: $transaction=$this->getDbConnection()->beginTransaction();
77: try
78: {
79: if($this->safeDown()===false)
80: {
81: $transaction->rollback();
82: return false;
83: }
84: $transaction->commit();
85: }
86: catch(Exception $e)
87: {
88: echo "Exception: ".$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
89: echo $e->getTraceAsString()."\n";
90: $transaction->rollback();
91: return false;
92: }
93: }
94:
95: /**
96: * This method contains the logic to be executed when applying this migration.
97: * This method differs from {@link up} in that the DB logic implemented here will
98: * be enclosed within a DB transaction.
99: * Child classes may implement this method instead of {@link up} if the DB logic
100: * needs to be within a transaction.
101: * @return boolean Returning false means, the migration will not be applied and
102: * the transaction will be rolled back.
103: * @since 1.1.7
104: */
105: public function safeUp()
106: {
107: }
108:
109: /**
110: * This method contains the logic to be executed when removing this migration.
111: * This method differs from {@link down} in that the DB logic implemented here will
112: * be enclosed within a DB transaction.
113: * Child classes may implement this method instead of {@link up} if the DB logic
114: * needs to be within a transaction.
115: * @return boolean Returning false means, the migration will not be applied and
116: * the transaction will be rolled back.
117: * @since 1.1.7
118: */
119: public function safeDown()
120: {
121: }
122:
123: /**
124: * Returns the currently active database connection.
125: * By default, the 'db' application component will be returned and activated.
126: * You can call {@link setDbConnection} to switch to a different database connection.
127: * Methods such as {@link insert}, {@link createTable} will use this database connection
128: * to perform DB queries.
129: * @throws CException if "db" application component is not configured
130: * @return CDbConnection the currently active database connection
131: */
132: public function getDbConnection()
133: {
134: if($this->_db===null)
135: {
136: $this->_db=Yii::app()->getComponent('db');
137: if(!$this->_db instanceof CDbConnection)
138: throw new CException(Yii::t('yii', 'The "db" application component must be configured to be a CDbConnection object.'));
139: }
140: return $this->_db;
141: }
142:
143: /**
144: * Sets the currently active database connection.
145: * The database connection will be used by the methods such as {@link insert}, {@link createTable}.
146: * @param CDbConnection $db the database connection component
147: */
148: public function setDbConnection($db)
149: {
150: $this->_db=$db;
151: }
152:
153: /**
154: * Executes a SQL statement.
155: * This method executes the specified SQL statement using {@link dbConnection}.
156: * @param string $sql the SQL statement to be executed
157: * @param array $params input parameters (name=>value) for the SQL execution. See {@link CDbCommand::execute} for more details.
158: * @since 1.1.7
159: */
160: public function execute($sql, $params=array())
161: {
162: echo " > execute SQL: $sql ...";
163: $time=microtime(true);
164: $this->getDbConnection()->createCommand($sql)->execute($params);
165: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
166: }
167:
168: /**
169: * Creates and executes an INSERT SQL statement.
170: * The method will properly escape the column names, and bind the values to be inserted.
171: * @param string $table the table that new rows will be inserted into.
172: * @param array $columns the column data (name=>value) to be inserted into the table.
173: */
174: public function insert($table, $columns)
175: {
176: echo " > insert into $table ...";
177: $time=microtime(true);
178: $this->getDbConnection()->createCommand()->insert($table, $columns);
179: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
180: }
181:
182: /**
183: * Creates and executes an INSERT SQL statement with multiple data.
184: * The method will properly escape the column names, and bind the values to be inserted.
185: * @param string $table the table that new rows will be inserted into.
186: * @param array $data an array of various column data (name=>value) to be inserted into the table.
187: * @since 1.1.16
188: */
189: public function insertMultiple($table, $data)
190: {
191: echo " > insert into $table ...";
192: $time=microtime(true);
193: $builder=$this->getDbConnection()->getSchema()->getCommandBuilder();
194: $command=$builder->createMultipleInsertCommand($table,$data);
195: $command->execute();
196: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
197: }
198:
199: /**
200: * Creates and executes an UPDATE SQL statement.
201: * The method will properly escape the column names and bind the values to be updated.
202: * @param string $table the table to be updated.
203: * @param array $columns the column data (name=>value) to be updated.
204: * @param mixed $conditions the conditions that will be put in the WHERE part. Please
205: * refer to {@link CDbCommand::where} on how to specify conditions.
206: * @param array $params the parameters to be bound to the query.
207: */
208: public function update($table, $columns, $conditions='', $params=array())
209: {
210: echo " > update $table ...";
211: $time=microtime(true);
212: $this->getDbConnection()->createCommand()->update($table, $columns, $conditions, $params);
213: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
214: }
215:
216: /**
217: * Creates and executes a DELETE SQL statement.
218: * @param string $table the table where the data will be deleted from.
219: * @param mixed $conditions the conditions that will be put in the WHERE part. Please
220: * refer to {@link CDbCommand::where} on how to specify conditions.
221: * @param array $params the parameters to be bound to the query.
222: */
223: public function delete($table, $conditions='', $params=array())
224: {
225: echo " > delete from $table ...";
226: $time=microtime(true);
227: $this->getDbConnection()->createCommand()->delete($table, $conditions, $params);
228: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
229: }
230:
231: /**
232: * Builds and executes a SQL statement for creating a new DB table.
233: *
234: * The columns in the new table should be specified as name-definition pairs (e.g. 'name'=>'string'),
235: * where name stands for a column name which will be properly quoted by the method, and definition
236: * stands for the column type which can contain an abstract DB type.
237: * The {@link getColumnType} method will be invoked to convert any abstract type into a physical one.
238: *
239: * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
240: * inserted into the generated SQL.
241: *
242: * @param string $table the name of the table to be created. The name will be properly quoted by the method.
243: * @param array $columns the columns (name=>definition) in the new table.
244: * @param string $options additional SQL fragment that will be appended to the generated SQL.
245: */
246: public function createTable($table, $columns, $options=null)
247: {
248: echo " > create table $table ...";
249: $time=microtime(true);
250: $this->getDbConnection()->createCommand()->createTable($table, $columns, $options);
251: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
252: }
253:
254: /**
255: * Builds and executes a SQL statement for renaming a DB table.
256: * @param string $table the table to be renamed. The name will be properly quoted by the method.
257: * @param string $newName the new table name. The name will be properly quoted by the method.
258: */
259: public function renameTable($table, $newName)
260: {
261: echo " > rename table $table to $newName ...";
262: $time=microtime(true);
263: $this->getDbConnection()->createCommand()->renameTable($table, $newName);
264: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
265: }
266:
267: /**
268: * Builds and executes a SQL statement for dropping a DB table.
269: * @param string $table the table to be dropped. The name will be properly quoted by the method.
270: */
271: public function dropTable($table)
272: {
273: echo " > drop table $table ...";
274: $time=microtime(true);
275: $this->getDbConnection()->createCommand()->dropTable($table);
276: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
277: }
278:
279: /**
280: * Builds and executes a SQL statement for truncating a DB table.
281: * @param string $table the table to be truncated. The name will be properly quoted by the method.
282: */
283: public function truncateTable($table)
284: {
285: echo " > truncate table $table ...";
286: $time=microtime(true);
287: $this->getDbConnection()->createCommand()->truncateTable($table);
288: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
289: }
290:
291: /**
292: * Builds and executes a SQL statement for adding a new DB column.
293: * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
294: * @param string $column the name of the new column. The name will be properly quoted by the method.
295: * @param string $type the column type. The {@link 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 addColumn($table, $column, $type)
300: {
301: echo " > add column $column $type to table $table ...";
302: $time=microtime(true);
303: $this->getDbConnection()->createCommand()->addColumn($table, $column, $type);
304: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
305: }
306:
307: /**
308: * Builds and executes a SQL statement for dropping a DB column.
309: * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
310: * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
311: */
312: public function dropColumn($table, $column)
313: {
314: echo " > drop column $column from table $table ...";
315: $time=microtime(true);
316: $this->getDbConnection()->createCommand()->dropColumn($table, $column);
317: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
318: }
319:
320: /**
321: * Builds and executes a SQL statement for renaming a column.
322: * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
323: * @param string $name the old name of the column. The name will be properly quoted by the method.
324: * @param string $newName the new name of the column. The name will be properly quoted by the method.
325: */
326: public function renameColumn($table, $name, $newName)
327: {
328: echo " > rename column $name in table $table to $newName ...";
329: $time=microtime(true);
330: $this->getDbConnection()->createCommand()->renameColumn($table, $name, $newName);
331: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
332: }
333:
334: /**
335: * Builds and executes a SQL statement for changing the definition of a column.
336: * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
337: * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
338: * @param string $type the new column type. The {@link getColumnType} method will be invoked to convert abstract column type (if any)
339: * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
340: * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
341: */
342: public function alterColumn($table, $column, $type)
343: {
344: echo " > alter column $column in table $table to $type ...";
345: $time=microtime(true);
346: $this->getDbConnection()->createCommand()->alterColumn($table, $column, $type);
347: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
348: }
349:
350: /**
351: * Builds a SQL statement for adding a foreign key constraint to an existing table.
352: * The method will properly quote the table and column names.
353: * @param string $name the name of the foreign key constraint.
354: * @param string $table the table that the foreign key constraint will be added to.
355: * @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 pass as an array of column names.
356: * @param string $refTable the table that the foreign key references to.
357: * @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 pass as an array of column names.
358: * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
359: * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
360: */
361: public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
362: {
363: echo " > add foreign key $name: $table (".(is_array($columns) ? implode(',', $columns) : $columns).
364: ") references $refTable (".(is_array($refColumns) ? implode(',', $refColumns) : $refColumns).") ...";
365: $time=microtime(true);
366: $this->getDbConnection()->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
367: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
368: }
369:
370: /**
371: * Builds a SQL statement for dropping a foreign key constraint.
372: * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
373: * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
374: */
375: public function dropForeignKey($name, $table)
376: {
377: echo " > drop foreign key $name from table $table ...";
378: $time=microtime(true);
379: $this->getDbConnection()->createCommand()->dropForeignKey($name, $table);
380: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
381: }
382:
383: /**
384: * Builds and executes a SQL statement for creating a new index.
385: * @param string $name the name of the index. The name will be properly quoted by the method.
386: * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
387: * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
388: * by commas or pass as an array of column names. Each column name will be properly quoted by the method, unless a parenthesis is found in the name.
389: * @param boolean $unique whether to add UNIQUE constraint on the created index.
390: */
391: public function createIndex($name, $table, $columns, $unique=false)
392: {
393: echo " > create".($unique ? ' unique':'')." index $name on $table (".(is_array($columns) ? implode(',', $columns) : $columns).") ...";
394: $time=microtime(true);
395: $this->getDbConnection()->createCommand()->createIndex($name, $table, $columns, $unique);
396: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
397: }
398:
399: /**
400: * Builds and executes a SQL statement for dropping an index.
401: * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
402: * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
403: */
404: public function dropIndex($name, $table)
405: {
406: echo " > drop index $name ...";
407: $time=microtime(true);
408: $this->getDbConnection()->createCommand()->dropIndex($name, $table);
409: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
410: }
411:
412: /**
413: * Refreshed schema cache for a table
414: * @param string $table name of the table to refresh
415: * @since 1.1.9
416: */
417: public function refreshTableSchema($table)
418: {
419: echo " > refresh table $table schema cache ...";
420: $time=microtime(true);
421: $this->getDbConnection()->getSchema()->getTable($table,true);
422: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
423: }
424:
425: /**
426: * Builds and executes a SQL statement for creating a primary key, supports composite primary keys.
427: * @param string $name name of the primary key constraint to add
428: * @param string $table name of the table to add primary key to
429: * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
430: * Array value can be passed since 1.1.14.
431: * @since 1.1.13
432: */
433: public function addPrimaryKey($name,$table,$columns)
434: {
435: echo " > alter table $table add constraint $name primary key (".(is_array($columns) ? implode(',', $columns) : $columns).") ...";
436: $time=microtime(true);
437: $this->getDbConnection()->createCommand()->addPrimaryKey($name,$table,$columns);
438: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
439: }
440:
441: /**
442: * Builds and executes a SQL statement for removing a primary key, supports composite primary keys.
443: * @param string $name name of the constraint to remove
444: * @param string $table name of the table to remove primary key from
445: * @since 1.1.13
446: */
447: public function dropPrimaryKey($name,$table)
448: {
449: echo " > alter table $table drop primary key $name ...";
450: $time=microtime(true);
451: $this->getDbConnection()->createCommand()->dropPrimaryKey($name,$table);
452: echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
453: }
454: }
455: