SchemaShell.php 16 KB

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