SchemaShell.php 16 KB

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