MigrateCommand.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <?php
  2. /**
  3. * MigrateCommand 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. * MigrateCommand manages the database migrations.
  12. *
  13. * The implementation of this command and other supporting classes referenced
  14. * the yii-dbmigrations extension ((https://github.com/pieterclaerhout/yii-dbmigrations),
  15. * authored by Pieter Claerhout.
  16. *
  17. * Since version 1.1.11 this command will exit with the following exit codes:
  18. * <ul>
  19. * <li>0 on success</li>
  20. * <li>1 on general error</li>
  21. * <li>2 on failed migration.</li>
  22. * </ul>
  23. *
  24. * @author Qiang Xue <qiang.xue@gmail.com>
  25. * @package system.cli.commands
  26. * @since 1.1.6
  27. */
  28. class MigrateCommand extends CConsoleCommand
  29. {
  30. const BASE_MIGRATION='m000000_000000_base';
  31. /**
  32. * @var string the directory that stores the migrations. This must be specified
  33. * in terms of a path alias, and the corresponding directory must exist.
  34. * Defaults to 'application.migrations' (meaning 'protected/migrations').
  35. */
  36. public $migrationPath='application.migrations';
  37. /**
  38. * @var string the name of the table for keeping applied migration information.
  39. * This table will be automatically created if not exists. Defaults to 'tbl_migration'.
  40. * The table structure is: (version varchar(255) primary key, apply_time integer)
  41. */
  42. public $migrationTable='tbl_migration';
  43. /**
  44. * @var string the application component ID that specifies the database connection for
  45. * storing migration information. Defaults to 'db'.
  46. */
  47. public $connectionID='db';
  48. /**
  49. * @var string the path of the template file for generating new migrations. This
  50. * must be specified in terms of a path alias (e.g. application.migrations.template).
  51. * If not set, an internal template will be used.
  52. */
  53. public $templateFile;
  54. /**
  55. * @var string the default command action. It defaults to 'up'.
  56. */
  57. public $defaultAction='up';
  58. /**
  59. * @var boolean whether to execute the migration in an interactive mode. Defaults to true.
  60. * Set this to false when performing migration in a cron job or background process.
  61. */
  62. public $interactive=true;
  63. public function beforeAction($action,$params)
  64. {
  65. $path=Yii::getPathOfAlias($this->migrationPath);
  66. if($path===false || !is_dir($path))
  67. {
  68. echo 'Error: The migration directory does not exist: '.$this->migrationPath."\n";
  69. exit(1);
  70. }
  71. $this->migrationPath=$path;
  72. $yiiVersion=Yii::getVersion();
  73. echo "\nYii Migration Tool v1.0 (based on Yii v{$yiiVersion})\n\n";
  74. return parent::beforeAction($action,$params);
  75. }
  76. public function actionUp($args)
  77. {
  78. if(($migrations=$this->getNewMigrations())===array())
  79. {
  80. echo "No new migration found. Your system is up-to-date.\n";
  81. return 0;
  82. }
  83. $total=count($migrations);
  84. $step=isset($args[0]) ? (int)$args[0] : 0;
  85. if($step>0)
  86. $migrations=array_slice($migrations,0,$step);
  87. $n=count($migrations);
  88. if($n===$total)
  89. echo "Total $n new ".($n===1 ? 'migration':'migrations')." to be applied:\n";
  90. else
  91. echo "Total $n out of $total new ".($total===1 ? 'migration':'migrations')." to be applied:\n";
  92. foreach($migrations as $migration)
  93. echo " $migration\n";
  94. echo "\n";
  95. if($this->confirm('Apply the above '.($n===1 ? 'migration':'migrations')."?"))
  96. {
  97. foreach($migrations as $migration)
  98. {
  99. if($this->migrateUp($migration)===false)
  100. {
  101. echo "\nMigration failed. All later migrations are canceled.\n";
  102. return 2;
  103. }
  104. }
  105. echo "\nMigrated up successfully.\n";
  106. }
  107. }
  108. public function actionDown($args)
  109. {
  110. $step=isset($args[0]) ? (int)$args[0] : 1;
  111. if($step<1)
  112. {
  113. echo "Error: The step parameter must be greater than 0.\n";
  114. return 1;
  115. }
  116. if(($migrations=$this->getMigrationHistory($step))===array())
  117. {
  118. echo "No migration has been done before.\n";
  119. return 0;
  120. }
  121. $migrations=array_keys($migrations);
  122. $n=count($migrations);
  123. echo "Total $n ".($n===1 ? 'migration':'migrations')." to be reverted:\n";
  124. foreach($migrations as $migration)
  125. echo " $migration\n";
  126. echo "\n";
  127. if($this->confirm('Revert the above '.($n===1 ? 'migration':'migrations')."?"))
  128. {
  129. foreach($migrations as $migration)
  130. {
  131. if($this->migrateDown($migration)===false)
  132. {
  133. echo "\nMigration failed. All later migrations are canceled.\n";
  134. return 2;
  135. }
  136. }
  137. echo "\nMigrated down successfully.\n";
  138. }
  139. }
  140. public function actionRedo($args)
  141. {
  142. $step=isset($args[0]) ? (int)$args[0] : 1;
  143. if($step<1)
  144. {
  145. echo "Error: The step parameter must be greater than 0.\n";
  146. return 1;
  147. }
  148. if(($migrations=$this->getMigrationHistory($step))===array())
  149. {
  150. echo "No migration has been done before.\n";
  151. return 0;
  152. }
  153. $migrations=array_keys($migrations);
  154. $n=count($migrations);
  155. echo "Total $n ".($n===1 ? 'migration':'migrations')." to be redone:\n";
  156. foreach($migrations as $migration)
  157. echo " $migration\n";
  158. echo "\n";
  159. if($this->confirm('Redo the above '.($n===1 ? 'migration':'migrations')."?"))
  160. {
  161. foreach($migrations as $migration)
  162. {
  163. if($this->migrateDown($migration)===false)
  164. {
  165. echo "\nMigration failed. All later migrations are canceled.\n";
  166. return 2;
  167. }
  168. }
  169. foreach(array_reverse($migrations) as $migration)
  170. {
  171. if($this->migrateUp($migration)===false)
  172. {
  173. echo "\nMigration failed. All later migrations are canceled.\n";
  174. return 2;
  175. }
  176. }
  177. echo "\nMigration redone successfully.\n";
  178. }
  179. }
  180. public function actionTo($args)
  181. {
  182. if(isset($args[0]))
  183. $version=$args[0];
  184. else
  185. $this->usageError('Please specify which version to migrate to.');
  186. $originalVersion=$version;
  187. if(preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/',$version,$matches))
  188. $version='m'.$matches[1];
  189. else
  190. {
  191. echo "Error: The version option must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table).\n";
  192. return 1;
  193. }
  194. // try migrate up
  195. $migrations=$this->getNewMigrations();
  196. foreach($migrations as $i=>$migration)
  197. {
  198. if(strpos($migration,$version.'_')===0)
  199. return $this->actionUp(array($i+1));
  200. }
  201. // try migrate down
  202. $migrations=array_keys($this->getMigrationHistory(-1));
  203. foreach($migrations as $i=>$migration)
  204. {
  205. if(strpos($migration,$version.'_')===0)
  206. {
  207. if($i===0)
  208. {
  209. echo "Already at '$originalVersion'. Nothing needs to be done.\n";
  210. return 0;
  211. }
  212. else
  213. return $this->actionDown(array($i));
  214. }
  215. }
  216. echo "Error: Unable to find the version '$originalVersion'.\n";
  217. return 1;
  218. }
  219. public function actionMark($args)
  220. {
  221. if(isset($args[0]))
  222. $version=$args[0];
  223. else
  224. $this->usageError('Please specify which version to mark to.');
  225. $originalVersion=$version;
  226. if(preg_match('/^m?(\d{6}_\d{6})(_.*?)?$/',$version,$matches))
  227. $version='m'.$matches[1];
  228. else {
  229. echo "Error: The version option must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table).\n";
  230. return 1;
  231. }
  232. $db=$this->getDbConnection();
  233. // try mark up
  234. $migrations=$this->getNewMigrations();
  235. foreach($migrations as $i=>$migration)
  236. {
  237. if(strpos($migration,$version.'_')===0)
  238. {
  239. if($this->confirm("Set migration history at $originalVersion?"))
  240. {
  241. $command=$db->createCommand();
  242. for($j=0;$j<=$i;++$j)
  243. {
  244. $command->insert($this->migrationTable, array(
  245. 'version'=>$migrations[$j],
  246. 'apply_time'=>time(),
  247. ));
  248. }
  249. echo "The migration history is set at $originalVersion.\nNo actual migration was performed.\n";
  250. }
  251. return 0;
  252. }
  253. }
  254. // try mark down
  255. $migrations=array_keys($this->getMigrationHistory(-1));
  256. foreach($migrations as $i=>$migration)
  257. {
  258. if(strpos($migration,$version.'_')===0)
  259. {
  260. if($i===0)
  261. echo "Already at '$originalVersion'. Nothing needs to be done.\n";
  262. else
  263. {
  264. if($this->confirm("Set migration history at $originalVersion?"))
  265. {
  266. $command=$db->createCommand();
  267. for($j=0;$j<$i;++$j)
  268. $command->delete($this->migrationTable, $db->quoteColumnName('version').'=:version', array(':version'=>$migrations[$j]));
  269. echo "The migration history is set at $originalVersion.\nNo actual migration was performed.\n";
  270. }
  271. }
  272. return 0;
  273. }
  274. }
  275. echo "Error: Unable to find the version '$originalVersion'.\n";
  276. return 1;
  277. }
  278. public function actionHistory($args)
  279. {
  280. $limit=isset($args[0]) ? (int)$args[0] : -1;
  281. $migrations=$this->getMigrationHistory($limit);
  282. if($migrations===array())
  283. echo "No migration has been done before.\n";
  284. else
  285. {
  286. $n=count($migrations);
  287. if($limit>0)
  288. echo "Showing the last $n applied ".($n===1 ? 'migration' : 'migrations').":\n";
  289. else
  290. echo "Total $n ".($n===1 ? 'migration has' : 'migrations have')." been applied before:\n";
  291. foreach($migrations as $version=>$time)
  292. echo " (".date('Y-m-d H:i:s',$time).') '.$version."\n";
  293. }
  294. }
  295. public function actionNew($args)
  296. {
  297. $limit=isset($args[0]) ? (int)$args[0] : -1;
  298. $migrations=$this->getNewMigrations();
  299. if($migrations===array())
  300. echo "No new migrations found. Your system is up-to-date.\n";
  301. else
  302. {
  303. $n=count($migrations);
  304. if($limit>0 && $n>$limit)
  305. {
  306. $migrations=array_slice($migrations,0,$limit);
  307. echo "Showing $limit out of $n new ".($n===1 ? 'migration' : 'migrations').":\n";
  308. }
  309. else
  310. echo "Found $n new ".($n===1 ? 'migration' : 'migrations').":\n";
  311. foreach($migrations as $migration)
  312. echo " ".$migration."\n";
  313. }
  314. }
  315. public function actionCreate($args)
  316. {
  317. if(isset($args[0]))
  318. $name=$args[0];
  319. else
  320. $this->usageError('Please provide the name of the new migration.');
  321. if(!preg_match('/^\w+$/',$name)) {
  322. echo "Error: The name of the migration must contain letters, digits and/or underscore characters only.\n";
  323. return 1;
  324. }
  325. $name='m'.gmdate('ymd_His').'_'.$name;
  326. $content=strtr($this->getTemplate(), array('{ClassName}'=>$name));
  327. $file=$this->migrationPath.DIRECTORY_SEPARATOR.$name.'.php';
  328. if($this->confirm("Create new migration '$file'?"))
  329. {
  330. file_put_contents($file, $content);
  331. echo "New migration created successfully.\n";
  332. }
  333. }
  334. public function confirm($message,$default=false)
  335. {
  336. if(!$this->interactive)
  337. return true;
  338. return parent::confirm($message,$default);
  339. }
  340. protected function migrateUp($class)
  341. {
  342. if($class===self::BASE_MIGRATION)
  343. return;
  344. echo "*** applying $class\n";
  345. $start=microtime(true);
  346. $migration=$this->instantiateMigration($class);
  347. if($migration->up()!==false)
  348. {
  349. $this->getDbConnection()->createCommand()->insert($this->migrationTable, array(
  350. 'version'=>$class,
  351. 'apply_time'=>time(),
  352. ));
  353. $time=microtime(true)-$start;
  354. echo "*** applied $class (time: ".sprintf("%.3f",$time)."s)\n\n";
  355. }
  356. else
  357. {
  358. $time=microtime(true)-$start;
  359. echo "*** failed to apply $class (time: ".sprintf("%.3f",$time)."s)\n\n";
  360. return false;
  361. }
  362. }
  363. protected function migrateDown($class)
  364. {
  365. if($class===self::BASE_MIGRATION)
  366. return;
  367. echo "*** reverting $class\n";
  368. $start=microtime(true);
  369. $migration=$this->instantiateMigration($class);
  370. if($migration->down()!==false)
  371. {
  372. $db=$this->getDbConnection();
  373. $db->createCommand()->delete($this->migrationTable, $db->quoteColumnName('version').'=:version', array(':version'=>$class));
  374. $time=microtime(true)-$start;
  375. echo "*** reverted $class (time: ".sprintf("%.3f",$time)."s)\n\n";
  376. }
  377. else
  378. {
  379. $time=microtime(true)-$start;
  380. echo "*** failed to revert $class (time: ".sprintf("%.3f",$time)."s)\n\n";
  381. return false;
  382. }
  383. }
  384. protected function instantiateMigration($class)
  385. {
  386. $file=$this->migrationPath.DIRECTORY_SEPARATOR.$class.'.php';
  387. require_once($file);
  388. $migration=new $class;
  389. $migration->setDbConnection($this->getDbConnection());
  390. return $migration;
  391. }
  392. /**
  393. * @var CDbConnection
  394. */
  395. private $_db;
  396. protected function getDbConnection()
  397. {
  398. if($this->_db!==null)
  399. return $this->_db;
  400. elseif(($this->_db=Yii::app()->getComponent($this->connectionID)) instanceof CDbConnection)
  401. return $this->_db;
  402. echo "Error: CMigrationCommand.connectionID '{$this->connectionID}' is invalid. Please make sure it refers to the ID of a CDbConnection application component.\n";
  403. exit(1);
  404. }
  405. protected function getMigrationHistory($limit)
  406. {
  407. $db=$this->getDbConnection();
  408. if($db->schema->getTable($this->migrationTable,true)===null)
  409. {
  410. $this->createMigrationHistoryTable();
  411. }
  412. return CHtml::listData($db->createCommand()
  413. ->select('version, apply_time')
  414. ->from($this->migrationTable)
  415. ->order('version DESC')
  416. ->limit($limit)
  417. ->queryAll(), 'version', 'apply_time');
  418. }
  419. protected function createMigrationHistoryTable()
  420. {
  421. $db=$this->getDbConnection();
  422. echo 'Creating migration history table "'.$this->migrationTable.'"...';
  423. $db->createCommand()->createTable($this->migrationTable,array(
  424. 'version'=>'string NOT NULL PRIMARY KEY',
  425. 'apply_time'=>'integer',
  426. ));
  427. $db->createCommand()->insert($this->migrationTable,array(
  428. 'version'=>self::BASE_MIGRATION,
  429. 'apply_time'=>time(),
  430. ));
  431. echo "done.\n";
  432. }
  433. protected function getNewMigrations()
  434. {
  435. $applied=array();
  436. foreach($this->getMigrationHistory(-1) as $version=>$time)
  437. $applied[substr($version,1,13)]=true;
  438. $migrations=array();
  439. $handle=opendir($this->migrationPath);
  440. while(($file=readdir($handle))!==false)
  441. {
  442. if($file==='.' || $file==='..')
  443. continue;
  444. $path=$this->migrationPath.DIRECTORY_SEPARATOR.$file;
  445. if(preg_match('/^(m(\d{6}_\d{6})_.*?)\.php$/',$file,$matches) && is_file($path) && !isset($applied[$matches[2]]))
  446. $migrations[]=$matches[1];
  447. }
  448. closedir($handle);
  449. sort($migrations);
  450. return $migrations;
  451. }
  452. public function getHelp()
  453. {
  454. return <<<EOD
  455. USAGE
  456. yiic migrate [action] [parameter]
  457. DESCRIPTION
  458. This command provides support for database migrations. The optional
  459. 'action' parameter specifies which specific migration task to perform.
  460. It can take these values: up, down, to, create, history, new, mark.
  461. If the 'action' parameter is not given, it defaults to 'up'.
  462. Each action takes different parameters. Their usage can be found in
  463. the following examples.
  464. EXAMPLES
  465. * yiic migrate
  466. Applies ALL new migrations. This is equivalent to 'yiic migrate up'.
  467. * yiic migrate create create_user_table
  468. Creates a new migration named 'create_user_table'.
  469. * yiic migrate up 3
  470. Applies the next 3 new migrations.
  471. * yiic migrate down
  472. Reverts the last applied migration.
  473. * yiic migrate down 3
  474. Reverts the last 3 applied migrations.
  475. * yiic migrate to 101129_185401
  476. Migrates up or down to version 101129_185401.
  477. * yiic migrate mark 101129_185401
  478. Modifies the migration history up or down to version 101129_185401.
  479. No actual migration will be performed.
  480. * yiic migrate history
  481. Shows all previously applied migration information.
  482. * yiic migrate history 10
  483. Shows the last 10 applied migrations.
  484. * yiic migrate new
  485. Shows all new migrations.
  486. * yiic migrate new 10
  487. Shows the next 10 migrations that have not been applied.
  488. EOD;
  489. }
  490. protected function getTemplate()
  491. {
  492. if($this->templateFile!==null)
  493. return file_get_contents(Yii::getPathOfAlias($this->templateFile).'.php');
  494. else
  495. return <<<EOD
  496. <?php
  497. class {ClassName} extends CDbMigration
  498. {
  499. public function up()
  500. {
  501. }
  502. public function down()
  503. {
  504. echo "{ClassName} does not support migration down.\\n";
  505. return false;
  506. }
  507. /*
  508. // Use safeUp/safeDown to do migration with transaction
  509. public function safeUp()
  510. {
  511. }
  512. public function safeDown()
  513. {
  514. }
  515. */
  516. }
  517. EOD;
  518. }
  519. }