SchemaShell.php 16 KB

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