SchemaShell.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. <?php
  2. /**
  3. * Command-line database management utility to automate programmer chores.
  4. *
  5. * Schema is CakePHP's database management utility. This helps you maintain versions of
  6. * of your database.
  7. *
  8. * PHP 5
  9. *
  10. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  11. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  12. *
  13. * Licensed under The MIT License
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @since CakePHP(tm) v 1.2.0.5550
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('File', 'Utility');
  22. App::uses('Folder', 'Utility');
  23. App::uses('CakeSchema', 'Model');
  24. /**
  25. * Schema is a command-line database management utility for automating programmer chores.
  26. *
  27. * @package Cake.Console.Command
  28. * @link http://book.cakephp.org/view/1523/Schema-management-and-migrations
  29. */
  30. class SchemaShell extends Shell {
  31. /**
  32. * Schema class being used.
  33. *
  34. * @var CakeSchema
  35. */
  36. public $Schema;
  37. /**
  38. * is this a dry run?
  39. *
  40. * @var boolean
  41. */
  42. protected $_dry = null;
  43. /**
  44. * Override initialize
  45. *
  46. * @return string
  47. */
  48. public function initialize() {
  49. $this->_welcome();
  50. $this->out('Cake Schema Shell');
  51. $this->hr();
  52. }
  53. /**
  54. * Override startup
  55. *
  56. * @return void
  57. */
  58. public function startup() {
  59. $name = $path = $connection = $plugin = null;
  60. if (!empty($this->params['name'])) {
  61. $name = $this->params['name'];
  62. } elseif (!empty($this->args[0])) {
  63. $name = $this->params['name'] = $this->args[0];
  64. }
  65. if (strpos($name, '.')) {
  66. list($this->params['plugin'], $splitName) = pluginSplit($name);
  67. $name = $this->params['name'] = $splitName;
  68. }
  69. if ($name) {
  70. $this->params['file'] = Inflector::underscore($name);
  71. }
  72. if (empty($this->params['file'])) {
  73. $this->params['file'] = 'schema.php';
  74. }
  75. if (strpos($this->params['file'], '.php') === false) {
  76. $this->params['file'] .= '.php';
  77. }
  78. $file = $this->params['file'];
  79. if (!empty($this->params['path'])) {
  80. $path = $this->params['path'];
  81. }
  82. if (!empty($this->params['connection'])) {
  83. $connection = $this->params['connection'];
  84. }
  85. if (!empty($this->params['plugin'])) {
  86. $plugin = $this->params['plugin'];
  87. if (empty($name)) {
  88. $name = $plugin;
  89. }
  90. }
  91. $this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
  92. }
  93. /**
  94. * Read and output contents of schema object
  95. * path to read as second arg
  96. *
  97. * @return void
  98. */
  99. public function view() {
  100. $File = new File($this->Schema->path . DS . $this->params['file']);
  101. if ($File->exists()) {
  102. $this->out($File->read());
  103. $this->_stop();
  104. } else {
  105. $file = $this->Schema->path . DS . $this->params['file'];
  106. $this->err(__d('cake_console', 'Schema file (%s) could not be found.', $file));
  107. $this->_stop();
  108. }
  109. }
  110. /**
  111. * Read database and Write schema object
  112. * accepts a connection as first arg or path to save as second arg
  113. *
  114. * @return void
  115. */
  116. public function generate() {
  117. $this->out(__d('cake_console', 'Generating Schema...'));
  118. $options = array();
  119. if ($this->params['force']) {
  120. $options = array('models' => false);
  121. }
  122. $snapshot = false;
  123. if (isset($this->args[0]) && $this->args[0] === 'snapshot') {
  124. $snapshot = true;
  125. }
  126. if (!$snapshot && file_exists($this->Schema->path . DS . $this->params['file'])) {
  127. $snapshot = true;
  128. $prompt = __d('cake_console', "Schema file exists.\n [O]verwrite\n [S]napshot\n [Q]uit\nWould you like to do?");
  129. $result = strtolower($this->in($prompt, array('o', 's', 'q'), 's'));
  130. if ($result === 'q') {
  131. return $this->_stop();
  132. }
  133. if ($result === 'o') {
  134. $snapshot = false;
  135. }
  136. }
  137. $cacheDisable = Configure::read('Cache.disable');
  138. Configure::write('Cache.disable', true);
  139. $content = $this->Schema->read($options);
  140. $content['file'] = $this->params['file'];
  141. Configure::write('Cache.disable', $cacheDisable);
  142. if ($snapshot === true) {
  143. $Folder = new Folder($this->Schema->path);
  144. $result = $Folder->read();
  145. $numToUse = false;
  146. if (isset($this->params['snapshot'])) {
  147. $numToUse = $this->params['snapshot'];
  148. }
  149. $count = 0;
  150. if (!empty($result[1])) {
  151. foreach ($result[1] as $file) {
  152. if (preg_match('/schema(?:[_\d]*)?\.php$/', $file)) {
  153. $count++;
  154. }
  155. }
  156. }
  157. if ($numToUse !== false) {
  158. if ($numToUse > $count) {
  159. $count = $numToUse;
  160. }
  161. }
  162. $fileName = rtrim($this->params['file'], '.php');
  163. $content['file'] = $fileName . '_' . $count . '.php';
  164. }
  165. if ($this->Schema->write($content)) {
  166. $this->out(__d('cake_console', 'Schema file: %s generated', $content['file']));
  167. $this->_stop();
  168. } else {
  169. $this->err(__d('cake_console', 'Schema file: %s generated'));
  170. $this->_stop();
  171. }
  172. }
  173. /**
  174. * Dump Schema object to sql file
  175. * Use the `write` param to enable and control SQL file output location.
  176. * Simply using -write will write the sql file to the same dir as the schema file.
  177. * If -write contains a full path name the file will be saved there. If -write only
  178. * contains no DS, that will be used as the file name, in the same dir as the schema file.
  179. *
  180. * @return string
  181. */
  182. public function dump() {
  183. $write = false;
  184. $Schema = $this->Schema->load();
  185. if (!$Schema) {
  186. $this->err(__d('cake_console', 'Schema could not be loaded'));
  187. $this->_stop();
  188. }
  189. if (!empty($this->params['write'])) {
  190. if ($this->params['write'] == 1) {
  191. $write = Inflector::underscore($this->Schema->name);
  192. } else {
  193. $write = $this->params['write'];
  194. }
  195. }
  196. $db = ConnectionManager::getDataSource($this->Schema->connection);
  197. $contents = "#" . $Schema->name . " sql generated on: " . date('Y-m-d H:i:s') . " : " . time() . "\n\n";
  198. $contents .= $db->dropSchema($Schema) . "\n\n". $db->createSchema($Schema);
  199. if ($write) {
  200. if (strpos($write, '.sql') === false) {
  201. $write .= '.sql';
  202. }
  203. if (strpos($write, DS) !== false) {
  204. $File = new File($write, true);
  205. } else {
  206. $File = new File($this->Schema->path . DS . $write, true);
  207. }
  208. if ($File->write($contents)) {
  209. $this->out(__d('cake_console', 'SQL dump file created in %s', $File->pwd()));
  210. $this->_stop();
  211. } else {
  212. $this->err(__d('cake_console', 'SQL dump could not be created'));
  213. $this->_stop();
  214. }
  215. }
  216. $this->out($contents);
  217. return $contents;
  218. }
  219. /**
  220. * Run database create commands. Alias for run create.
  221. *
  222. * @return void
  223. */
  224. public function create() {
  225. list($Schema, $table) = $this->_loadSchema();
  226. $this->_create($Schema, $table);
  227. }
  228. /**
  229. * Run database create commands. Alias for run create.
  230. *
  231. * @return void
  232. */
  233. public function update() {
  234. list($Schema, $table) = $this->_loadSchema();
  235. $this->_update($Schema, $table);
  236. }
  237. /**
  238. * Prepares the Schema objects for database operations.
  239. *
  240. * @return void
  241. */
  242. protected function _loadSchema() {
  243. $name = $plugin = null;
  244. if (!empty($this->params['name'])) {
  245. $name = $this->params['name'];
  246. }
  247. if (!empty($this->params['plugin'])) {
  248. $plugin = $this->params['plugin'];
  249. }
  250. if (!empty($this->params['dry'])) {
  251. $this->_dry = true;
  252. $this->out(__d('cake_console', 'Performing a dry run.'));
  253. }
  254. $options = array('name' => $name, 'plugin' => $plugin);
  255. if (!empty($this->params['snapshot'])) {
  256. $fileName = rtrim($this->Schema->file, '.php');
  257. $options['file'] = $fileName . '_' . $this->params['snapshot'] . '.php';
  258. }
  259. $Schema = $this->Schema->load($options);
  260. if (!$Schema) {
  261. $this->err(__d('cake_console', '%s could not be loaded', $this->Schema->path . DS . $this->Schema->file));
  262. $this->_stop();
  263. }
  264. $table = null;
  265. if (isset($this->args[1])) {
  266. $table = $this->args[1];
  267. }
  268. return array(&$Schema, $table);
  269. }
  270. /**
  271. * Create database from Schema object
  272. * Should be called via the run method
  273. *
  274. * @param CakeSchema $Schema
  275. * @param string $table
  276. * @return void
  277. */
  278. protected function _create($Schema, $table = null) {
  279. $db = ConnectionManager::getDataSource($this->Schema->connection);
  280. $drop = $create = array();
  281. if (!$table) {
  282. foreach ($Schema->tables as $table => $fields) {
  283. $drop[$table] = $db->dropSchema($Schema, $table);
  284. $create[$table] = $db->createSchema($Schema, $table);
  285. }
  286. } elseif (isset($Schema->tables[$table])) {
  287. $drop[$table] = $db->dropSchema($Schema, $table);
  288. $create[$table] = $db->createSchema($Schema, $table);
  289. }
  290. if (empty($drop) || empty($create)) {
  291. $this->out(__d('cake_console', 'Schema is up to date.'));
  292. $this->_stop();
  293. }
  294. $this->out("\n" . __d('cake_console', 'The following table(s) will be dropped.'));
  295. $this->out(array_keys($drop));
  296. if ('y' == $this->in(__d('cake_console', 'Are you sure you want to drop the table(s)?'), array('y', 'n'), 'n')) {
  297. $this->out(__d('cake_console', 'Dropping table(s).'));
  298. $this->_run($drop, 'drop', $Schema);
  299. }
  300. $this->out("\n" . __d('cake_console', 'The following table(s) will be created.'));
  301. $this->out(array_keys($create));
  302. if ('y' == $this->in(__d('cake_console', 'Are you sure you want to create the table(s)?'), array('y', 'n'), 'y')) {
  303. $this->out(__d('cake_console', 'Creating table(s).'));
  304. $this->_run($create, 'create', $Schema);
  305. }
  306. $this->out(__d('cake_console', 'End create.'));
  307. }
  308. /**
  309. * Update database with Schema object
  310. * Should be called via the run method
  311. *
  312. * @param CakeSchema $Schema
  313. * @param string $table
  314. * @return void
  315. */
  316. protected function _update(&$Schema, $table = null) {
  317. $db = ConnectionManager::getDataSource($this->Schema->connection);
  318. $this->out(__d('cake_console', 'Comparing Database to Schema...'));
  319. $options = array();
  320. if (isset($this->params['force'])) {
  321. $options['models'] = false;
  322. }
  323. $Old = $this->Schema->read($options);
  324. $compare = $this->Schema->compare($Old, $Schema);
  325. $contents = array();
  326. if (empty($table)) {
  327. foreach ($compare as $table => $changes) {
  328. $contents[$table] = $db->alterSchema(array($table => $changes), $table);
  329. }
  330. } elseif (isset($compare[$table])) {
  331. $contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
  332. }
  333. if (empty($contents)) {
  334. $this->out(__d('cake_console', 'Schema is up to date.'));
  335. $this->_stop();
  336. }
  337. $this->out("\n" . __d('cake_console', 'The following statements will run.'));
  338. $this->out(array_map('trim', $contents));
  339. if ('y' == $this->in(__d('cake_console', 'Are you sure you want to alter the tables?'), array('y', 'n'), 'n')) {
  340. $this->out();
  341. $this->out(__d('cake_console', 'Updating Database...'));
  342. $this->_run($contents, 'update', $Schema);
  343. }
  344. $this->out(__d('cake_console', 'End update.'));
  345. }
  346. /**
  347. * Runs sql from _create() or _update()
  348. *
  349. * @param array $contents
  350. * @param string $event
  351. * @param CakeSchema $Schema
  352. * @return void
  353. */
  354. protected function _run($contents, $event, &$Schema) {
  355. if (empty($contents)) {
  356. $this->err(__d('cake_console', 'Sql could not be run'));
  357. return;
  358. }
  359. Configure::write('debug', 2);
  360. $db = ConnectionManager::getDataSource($this->Schema->connection);
  361. foreach ($contents as $table => $sql) {
  362. if (empty($sql)) {
  363. $this->out(__d('cake_console', '%s is up to date.', $table));
  364. } else {
  365. if ($this->_dry === true) {
  366. $this->out(__d('cake_console', 'Dry run for %s :', $table));
  367. $this->out($sql);
  368. } else {
  369. if (!$Schema->before(array($event => $table))) {
  370. return false;
  371. }
  372. $error = null;
  373. try {
  374. $db->execute($sql);
  375. } catch (PDOException $e) {
  376. $error = $table . ': ' . $e->getMessage();
  377. }
  378. $Schema->after(array($event => $table, 'errors' => $error));
  379. if (!empty($error)) {
  380. $this->out($error);
  381. } else {
  382. $this->out(__d('cake_console', '%s updated.', $table));
  383. }
  384. }
  385. }
  386. }
  387. }
  388. /**
  389. * get the option parser
  390. *
  391. * @return void
  392. */
  393. public function getOptionParser() {
  394. $plugin = array(
  395. 'help' => __d('cake_console', 'The plugin to use.'),
  396. );
  397. $connection = array(
  398. 'help' => __d('cake_console', 'Set the db config to use.'),
  399. 'default' => 'default'
  400. );
  401. $path = array(
  402. 'help' => __d('cake_console', 'Path to read and write schema.php'),
  403. 'default' => APP . 'Config' . DS . 'Schema'
  404. );
  405. $file = array(
  406. 'help' => __d('cake_console', 'File name to read and write.'),
  407. 'default' => 'schema.php'
  408. );
  409. $name = array(
  410. 'help' => __d('cake_console', 'Classname to use. If its Plugin.class, both name and plugin options will be set.')
  411. );
  412. $snapshot = array(
  413. 'short' => 's',
  414. 'help' => __d('cake_console', 'Snapshot number to use/make.')
  415. );
  416. $dry = array(
  417. 'help' => __d('cake_console', 'Perform a dry run on create and update commands. Queries will be output instead of run.'),
  418. 'boolean' => true
  419. );
  420. $force = array(
  421. 'short' => 'f',
  422. 'help' => __d('cake_console', 'Force "generate" to create a new schema'),
  423. 'boolean' => true
  424. );
  425. $write = array(
  426. 'help' => __d('cake_console', 'Write the dumped SQL to a file.')
  427. );
  428. $parser = parent::getOptionParser();
  429. $parser->description(
  430. __d('cake_console', 'The Schema Shell generates a schema object from the database and updates the database from the schema.')
  431. )->addSubcommand('view', array(
  432. 'help' => __d('cake_console', 'Read and output the contents of a schema file'),
  433. 'parser' => array(
  434. 'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
  435. 'arguments' => compact('name')
  436. )
  437. ))->addSubcommand('generate', array(
  438. 'help' => __d('cake_console', 'Reads from --connection and writes to --path. Generate snapshots with -s'),
  439. 'parser' => array(
  440. 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'snapshot', 'force'),
  441. 'arguments' => array(
  442. 'snapshot' => array('help' => __d('cake_console', 'Generate a snapshot.'))
  443. )
  444. )
  445. ))->addSubcommand('dump', array(
  446. 'help' => __d('cake_console', 'Dump database SQL based on a schema file to stdout.'),
  447. 'parser' => array(
  448. 'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
  449. 'arguments' => compact('name')
  450. )
  451. ))->addSubcommand('create', array(
  452. 'help' => __d('cake_console', 'Drop and create tables based on the schema file.'),
  453. 'parser' => array(
  454. 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot'),
  455. 'args' => array(
  456. 'name' => array(
  457. 'help' => __d('cake_console', 'Name of schema to use.')
  458. ),
  459. 'table' => array(
  460. 'help' => __d('cake_console', 'Only create the specified table.')
  461. )
  462. )
  463. )
  464. ))->addSubcommand('update', array(
  465. 'help' => __d('cake_console', 'Alter the tables based on the schema file.'),
  466. 'parser' => array(
  467. 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot'),
  468. 'args' => array(
  469. 'name' => array(
  470. 'help' => __d('cake_console', 'Name of schema to use.')
  471. ),
  472. 'table' => array(
  473. 'help' => __d('cake_console', 'Only create the specified table.')
  474. )
  475. )
  476. )
  477. ));
  478. return $parser;
  479. }
  480. }