PageRenderTime 39ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Console/Command/SchemaShell.php

https://gitlab.com/fouzia23chowdhury/cakephpCRUD
PHP | 570 lines | 411 code | 57 blank | 102 comment | 64 complexity | 830d1cf6876da5f40a8e01a00f30ee3f MD5 | raw file
  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::camelize($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', '<error>Error</error>: 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(2);
  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 (!empty($this->params['yes']) ||
  299. $this->in(__d('cake_console', 'Are you sure you want to drop the table(s)?'), array('y', 'n'), 'n') === 'y'
  300. ) {
  301. $this->out(__d('cake_console', 'Dropping table(s).'));
  302. $this->_run($drop, 'drop', $Schema);
  303. }
  304. $this->out("\n" . __d('cake_console', 'The following table(s) will be created.'));
  305. $this->out(array_keys($create));
  306. if (!empty($this->params['yes']) ||
  307. $this->in(__d('cake_console', 'Are you sure you want to create the table(s)?'), array('y', 'n'), 'y') === 'y'
  308. ) {
  309. $this->out(__d('cake_console', 'Creating table(s).'));
  310. $this->_run($create, 'create', $Schema);
  311. }
  312. $this->out(__d('cake_console', 'End create.'));
  313. }
  314. /**
  315. * Update database with Schema object
  316. * Should be called via the run method
  317. *
  318. * @param CakeSchema &$Schema The schema instance
  319. * @param string $table The table name.
  320. * @return void
  321. */
  322. protected function _update(&$Schema, $table = null) {
  323. $db = ConnectionManager::getDataSource($this->Schema->connection);
  324. $this->out(__d('cake_console', 'Comparing Database to Schema...'));
  325. $options = array();
  326. if (isset($this->params['force'])) {
  327. $options['models'] = false;
  328. }
  329. $Old = $this->Schema->read($options);
  330. $compare = $this->Schema->compare($Old, $Schema);
  331. $contents = array();
  332. if (empty($table)) {
  333. foreach ($compare as $table => $changes) {
  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. } elseif (isset($compare[$table])) {
  341. if (isset($compare[$table]['create'])) {
  342. $contents[$table] = $db->createSchema($Schema, $table);
  343. } else {
  344. $contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
  345. }
  346. }
  347. if (empty($contents)) {
  348. $this->out(__d('cake_console', 'Schema is up to date.'));
  349. return $this->_stop();
  350. }
  351. $this->out("\n" . __d('cake_console', 'The following statements will run.'));
  352. $this->out(array_map('trim', $contents));
  353. if (!empty($this->params['yes']) ||
  354. $this->in(__d('cake_console', 'Are you sure you want to alter the tables?'), array('y', 'n'), 'n') === 'y'
  355. ) {
  356. $this->out();
  357. $this->out(__d('cake_console', 'Updating Database...'));
  358. $this->_run($contents, 'update', $Schema);
  359. }
  360. $this->out(__d('cake_console', 'End update.'));
  361. }
  362. /**
  363. * Runs sql from _create() or _update()
  364. *
  365. * @param array $contents The contents to execute.
  366. * @param string $event The event to fire
  367. * @param CakeSchema $Schema The schema instance.
  368. * @return void
  369. */
  370. protected function _run($contents, $event, CakeSchema $Schema) {
  371. if (empty($contents)) {
  372. $this->err(__d('cake_console', 'Sql could not be run'));
  373. return;
  374. }
  375. Configure::write('debug', 2);
  376. $db = ConnectionManager::getDataSource($this->Schema->connection);
  377. foreach ($contents as $table => $sql) {
  378. if (empty($sql)) {
  379. $this->out(__d('cake_console', '%s is up to date.', $table));
  380. } else {
  381. if ($this->_dry === true) {
  382. $this->out(__d('cake_console', 'Dry run for %s :', $table));
  383. $this->out($sql);
  384. } else {
  385. if (!$Schema->before(array($event => $table))) {
  386. return false;
  387. }
  388. $error = null;
  389. try {
  390. $db->execute($sql);
  391. } catch (PDOException $e) {
  392. $error = $table . ': ' . $e->getMessage();
  393. }
  394. $Schema->after(array($event => $table, 'errors' => $error));
  395. if (!empty($error)) {
  396. $this->err($error);
  397. } else {
  398. $this->out(__d('cake_console', '%s updated.', $table));
  399. }
  400. }
  401. }
  402. }
  403. }
  404. /**
  405. * Gets the option parser instance and configures it.
  406. *
  407. * @return ConsoleOptionParser
  408. */
  409. public function getOptionParser() {
  410. $parser = parent::getOptionParser();
  411. $plugin = array(
  412. 'short' => 'p',
  413. 'help' => __d('cake_console', 'The plugin to use.'),
  414. );
  415. $connection = array(
  416. 'short' => 'c',
  417. 'help' => __d('cake_console', 'Set the db config to use.'),
  418. 'default' => 'default'
  419. );
  420. $path = array(
  421. 'help' => __d('cake_console', 'Path to read and write schema.php'),
  422. 'default' => APP . 'Config' . DS . 'Schema'
  423. );
  424. $file = array(
  425. 'help' => __d('cake_console', 'File name to read and write.'),
  426. );
  427. $name = array(
  428. 'help' => __d('cake_console',
  429. 'Classname to use. If its Plugin.class, both name and plugin options will be set.'
  430. )
  431. );
  432. $snapshot = array(
  433. 'short' => 's',
  434. 'help' => __d('cake_console', 'Snapshot number to use/make.')
  435. );
  436. $models = array(
  437. 'short' => 'm',
  438. 'help' => __d('cake_console', 'Specify models as comma separated list.'),
  439. );
  440. $dry = array(
  441. 'help' => __d('cake_console',
  442. 'Perform a dry run on create and update commands. Queries will be output instead of run.'
  443. ),
  444. 'boolean' => true
  445. );
  446. $force = array(
  447. 'short' => 'f',
  448. 'help' => __d('cake_console', 'Force "generate" to create a new schema'),
  449. 'boolean' => true
  450. );
  451. $write = array(
  452. 'help' => __d('cake_console', 'Write the dumped SQL to a file.')
  453. );
  454. $exclude = array(
  455. 'help' => __d('cake_console', 'Tables to exclude as comma separated list.')
  456. );
  457. $yes = array(
  458. 'short' => 'y',
  459. 'help' => __d('cake_console', 'Do not prompt for confirmation. Be careful!'),
  460. 'boolean' => true
  461. );
  462. $parser->description(
  463. __d('cake_console', 'The Schema Shell generates a schema object from the database and updates the database from the schema.')
  464. )->addSubcommand('view', array(
  465. 'help' => __d('cake_console', 'Read and output the contents of a schema file'),
  466. 'parser' => array(
  467. 'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
  468. 'arguments' => compact('name')
  469. )
  470. ))->addSubcommand('generate', array(
  471. 'help' => __d('cake_console', 'Reads from --connection and writes to --path. Generate snapshots with -s'),
  472. 'parser' => array(
  473. 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'snapshot', 'force', 'models', 'exclude'),
  474. 'arguments' => array(
  475. 'snapshot' => array('help' => __d('cake_console', 'Generate a snapshot.'))
  476. )
  477. )
  478. ))->addSubcommand('dump', array(
  479. 'help' => __d('cake_console', 'Dump database SQL based on a schema file to stdout.'),
  480. 'parser' => array(
  481. 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'write'),
  482. 'arguments' => compact('name')
  483. )
  484. ))->addSubcommand('create', array(
  485. 'help' => __d('cake_console', 'Drop and create tables based on the schema file.'),
  486. 'parser' => array(
  487. 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot', 'yes'),
  488. 'args' => array(
  489. 'name' => array(
  490. 'help' => __d('cake_console', 'Name of schema to use.')
  491. ),
  492. 'table' => array(
  493. 'help' => __d('cake_console', 'Only create the specified table.')
  494. )
  495. )
  496. )
  497. ))->addSubcommand('update', array(
  498. 'help' => __d('cake_console', 'Alter the tables based on the schema file.'),
  499. 'parser' => array(
  500. 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot', 'force', 'yes'),
  501. 'args' => array(
  502. 'name' => array(
  503. 'help' => __d('cake_console', 'Name of schema to use.')
  504. ),
  505. 'table' => array(
  506. 'help' => __d('cake_console', 'Only create the specified table.')
  507. )
  508. )
  509. )
  510. ));
  511. return $parser;
  512. }
  513. }