PageRenderTime 45ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/yii/framework/cli/commands/MigrateCommand.php

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