SchemaShell.php 16 KB

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