Migration

Code sharing for migration. Maybe for someone this help.




class m110912_093959_fr_settings extends CDbMigration

{

	public function __construct()

	{

		Yii::app()->db->createCommand('SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;')->execute();

		Yii::app()->db->createCommand('SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;')->execute();

		Yii::app()->db->createCommand('SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE="TRADITIONAL";')->execute();

	}

	public function __destruct()

	{

		Yii::app()->db->createCommand('SET SQL_MODE=@OLD_SQL_MODE;')->execute();

		Yii::app()->db->createCommand('SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;')->execute();

		Yii::app()->db->createCommand('SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;')->execute();

	}

	public function safeUp()

	{

		$this->_checkTables();


		$this->createTable('_fr_settings',

			array(

				'id' => 'int(11) NOT NULL AUTO_INCREMENT', // auto increment

....

				'create_time' => 'int(11) NULL DEFAULT NULL',

				'update_time' => 'int(11) NULL DEFAULT NULL',

				'PRIMARY KEY (`id`)', // primary item

			),

			'ENGINE=InnoDB');

	}


	private function _checkTables ()

	{

		$tables = array('_fr_settings');

		$table_names = $this->getDbConnection()->getSchema()->getTableNames();

		foreach ($tables as $table) {

			if (in_array($table, $table_names)) {

				$this->dropTable($table);

			}

		}

	}


	public function safeDown()

	{

		$this->_checkTables();

	}

}



Hey,Thanks for sharing this code…very helpful.

Just a small correction:


                $this->createTable('_fr_settings',

                        array(

                                'id' => 'pk'

....

                                'create_time' => 'int(11) NULL DEFAULT NULL',

                                'update_time' => 'int(11) NULL DEFAULT NULL',

                        ),

                        'ENGINE=InnoDB');



instead of:


                $this->createTable('_fr_settings',

                        array(

                                'id' => 'int(11) NOT NULL AUTO_INCREMENT', // auto increment

....

                                'create_time' => 'int(11) NULL DEFAULT NULL',

                                'update_time' => 'int(11) NULL DEFAULT NULL',

                                'PRIMARY KEY (`id`)', // primary item

                        ),

                        'ENGINE=InnoDB');



But you can’t use the short ‘pk’ type if your primary key is not an int, though. ;)

To further jacmoe’s suggestions regarding “pk”, there are several shortcut data types that you can specify, as described here:

http://www.yiiframework.com/doc/api/1.1/CDbSchema#getColumnType-detail

instead of


Yii::app()->db->createCommand($sql)->execute();

you can write


$this->execute($sql);