PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

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

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