PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/Bancha/cakephp
PHP | 521 lines | 368 code | 53 blank | 100 comment | 64 complexity | dab6ffc37d42bb6230c84d255c98b53c MD5 | raw file
  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-2010, 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-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @package cake.console.shells
  19. * @since CakePHP(tm) v 1.2.0.5550
  20. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  21. */
  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. * @package cake.console.shells
  29. * @link http://book.cakephp.org/view/1523/Schema-management-and-migrations
  30. */
  31. class SchemaShell extends Shell {
  32. /**
  33. * is this a dry run?
  34. *
  35. * @var boolean
  36. * @access private
  37. */
  38. private $__dry = null;
  39. /**
  40. * Schema class being used.
  41. *
  42. * @var CakeSchema
  43. */
  44. public $Schema;
  45. /**
  46. * Override initialize
  47. *
  48. */
  49. public function initialize() {
  50. $this->_welcome();
  51. $this->out('Cake Schema Shell');
  52. $this->hr();
  53. }
  54. /**
  55. * Override startup
  56. *
  57. */
  58. public function startup() {
  59. $name = $path = $connection = $plugin = null;
  60. if (!empty($this->params['name'])) {
  61. $name = $this->params['name'];
  62. } elseif (!empty($this->args[0])) {
  63. $name = $this->params['name'] = $this->args[0];
  64. }
  65. if (strpos($name, '.')) {
  66. list($this->params['plugin'], $splitName) = pluginSplit($name);
  67. $name = $this->params['name'] = $splitName;
  68. }
  69. if ($name) {
  70. $this->params['file'] = Inflector::underscore($name);
  71. }
  72. if (empty($this->params['file'])) {
  73. $this->params['file'] = 'schema.php';
  74. }
  75. if (strpos($this->params['file'], '.php') === false) {
  76. $this->params['file'] .= '.php';
  77. }
  78. $file = $this->params['file'];
  79. if (!empty($this->params['path'])) {
  80. $path = $this->params['path'];
  81. }
  82. if (!empty($this->params['connection'])) {
  83. $connection = $this->params['connection'];
  84. }
  85. if (!empty($this->params['plugin'])) {
  86. $plugin = $this->params['plugin'];
  87. if (empty($name)) {
  88. $name = $plugin;
  89. }
  90. }
  91. $this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
  92. }
  93. /**
  94. * Read and output contents of schema object
  95. * path to read as second arg
  96. *
  97. */
  98. public function view() {
  99. $File = new File($this->Schema->path . DS . $this->params['file']);
  100. if ($File->exists()) {
  101. $this->out($File->read());
  102. $this->_stop();
  103. } else {
  104. $file = $this->Schema->path . DS . $this->params['file'];
  105. $this->err(__d('cake_console', 'Schema file (%s) could not be found.', $file));
  106. $this->_stop();
  107. }
  108. }
  109. /**
  110. * Read database and Write schema object
  111. * accepts a connection as first arg or path to save as second arg
  112. *
  113. */
  114. public function generate() {
  115. $this->out(__d('cake_console', 'Generating Schema...'));
  116. $options = array();
  117. if (isset($this->params['force'])) {
  118. $options = array('models' => false);
  119. }
  120. $snapshot = false;
  121. if (isset($this->args[0]) && $this->args[0] === 'snapshot') {
  122. $snapshot = true;
  123. }
  124. if (!$snapshot && file_exists($this->Schema->path . DS . $this->params['file'])) {
  125. $snapshot = true;
  126. $prompt = __d('cake_console', "Schema file exists.\n [O]verwrite\n [S]napshot\n [Q]uit\nWould you like to do?");
  127. $result = strtolower($this->in($prompt, array('o', 's', 'q'), 's'));
  128. if ($result === 'q') {
  129. return $this->_stop();
  130. }
  131. if ($result === 'o') {
  132. $snapshot = false;
  133. }
  134. }
  135. $cacheDisable = Configure::read('Cache.disable');
  136. Configure::write('Cache.disable', true);
  137. $content = $this->Schema->read($options);
  138. $content['file'] = $this->params['file'];
  139. Configure::write('Cache.disable', $cacheDisable);
  140. if ($snapshot === true) {
  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('/schema(?:[_\d]*)?\.php$/', $file)) {
  151. $count++;
  152. }
  153. }
  154. }
  155. if ($numToUse !== false) {
  156. if ($numToUse > $count) {
  157. $count = $numToUse;
  158. }
  159. }
  160. $fileName = rtrim($this->params['file'], '.php');
  161. $content['file'] = $fileName . '_' . $count . '.php';
  162. }
  163. if ($this->Schema->write($content)) {
  164. $this->out(__d('cake_console', 'Schema file: %s generated', $content['file']));
  165. $this->_stop();
  166. } else {
  167. $this->err(__d('cake_console', 'Schema file: %s generated'));
  168. $this->_stop();
  169. }
  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. */
  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 = "#" . $Schema->name . " sql generated on: " . date('Y-m-d H:i:s') . " : " . time() . "\n\n";
  195. $contents .= $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. $this->_stop();
  208. } else {
  209. $this->err(__d('cake_console', 'SQL dump could not be created'));
  210. $this->_stop();
  211. }
  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. 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. 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. 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', '%s could not be loaded', $this->Schema->path . DS . $this->Schema->file));
  259. $this->_stop();
  260. }
  261. $table = null;
  262. if (isset($this->args[1])) {
  263. $table = $this->args[1];
  264. }
  265. return array(&$Schema, $table);
  266. }
  267. /**
  268. * Create database from Schema object
  269. * Should be called via the run method
  270. *
  271. * @access private
  272. */
  273. function __create($Schema, $table = null) {
  274. $db = ConnectionManager::getDataSource($this->Schema->connection);
  275. $drop = $create = array();
  276. if (!$table) {
  277. foreach ($Schema->tables as $table => $fields) {
  278. $drop[$table] = $db->dropSchema($Schema, $table);
  279. $create[$table] = $db->createSchema($Schema, $table);
  280. }
  281. } elseif (isset($Schema->tables[$table])) {
  282. $drop[$table] = $db->dropSchema($Schema, $table);
  283. $create[$table] = $db->createSchema($Schema, $table);
  284. }
  285. if (empty($drop) || empty($create)) {
  286. $this->out(__d('cake_console', 'Schema is up to date.'));
  287. $this->_stop();
  288. }
  289. $this->out("\n" . __d('cake_console', 'The following table(s) will be dropped.'));
  290. $this->out(array_keys($drop));
  291. if ('y' == $this->in(__d('cake_console', 'Are you sure you want to drop the table(s)?'), array('y', 'n'), 'n')) {
  292. $this->out(__d('cake_console', 'Dropping table(s).'));
  293. $this->__run($drop, 'drop', $Schema);
  294. }
  295. $this->out("\n" . __d('cake_console', 'The following table(s) will be created.'));
  296. $this->out(array_keys($create));
  297. if ('y' == $this->in(__d('cake_console', 'Are you sure you want to create the table(s)?'), array('y', 'n'), 'y')) {
  298. $this->out(__d('cake_console', 'Creating table(s).'));
  299. $this->__run($create, 'create', $Schema);
  300. }
  301. $this->out(__d('cake_console', 'End create.'));
  302. }
  303. /**
  304. * Update database with Schema object
  305. * Should be called via the run method
  306. *
  307. * @access private
  308. */
  309. function __update(&$Schema, $table = null) {
  310. $db = ConnectionManager::getDataSource($this->Schema->connection);
  311. $this->out(__d('cake_console', 'Comparing Database to Schema...'));
  312. $options = array();
  313. if (isset($this->params['force'])) {
  314. $options['models'] = false;
  315. }
  316. $Old = $this->Schema->read($options);
  317. $compare = $this->Schema->compare($Old, $Schema);
  318. $contents = array();
  319. if (empty($table)) {
  320. foreach ($compare as $table => $changes) {
  321. $contents[$table] = $db->alterSchema(array($table => $changes), $table);
  322. }
  323. } elseif (isset($compare[$table])) {
  324. $contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
  325. }
  326. if (empty($contents)) {
  327. $this->out(__d('cake_console', 'Schema is up to date.'));
  328. $this->_stop();
  329. }
  330. $this->out("\n" . __d('cake_console', 'The following statements will run.'));
  331. $this->out(array_map('trim', $contents));
  332. if ('y' == $this->in(__d('cake_console', 'Are you sure you want to alter the tables?'), array('y', 'n'), 'n')) {
  333. $this->out();
  334. $this->out(__d('cake_console', 'Updating Database...'));
  335. $this->__run($contents, 'update', $Schema);
  336. }
  337. $this->out(__d('cake_console', 'End update.'));
  338. }
  339. /**
  340. * Runs sql from __create() or __update()
  341. *
  342. * @access private
  343. */
  344. function __run($contents, $event, &$Schema) {
  345. if (empty($contents)) {
  346. $this->err(__d('cake_console', 'Sql could not be run'));
  347. return;
  348. }
  349. Configure::write('debug', 2);
  350. $db = ConnectionManager::getDataSource($this->Schema->connection);
  351. foreach ($contents as $table => $sql) {
  352. if (empty($sql)) {
  353. $this->out(__d('cake_console', '%s is up to date.', $table));
  354. } else {
  355. if ($this->__dry === true) {
  356. $this->out(__d('cake_console', 'Dry run for %s :', $table));
  357. $this->out($sql);
  358. } else {
  359. if (!$Schema->before(array($event => $table))) {
  360. return false;
  361. }
  362. $error = null;
  363. if (!$db->execute($sql)) {
  364. $error = $table . ': ' . $db->lastError();
  365. }
  366. $Schema->after(array($event => $table, 'errors' => $error));
  367. if (!empty($error)) {
  368. $this->out($error);
  369. } else {
  370. $this->out(__d('cake_console', '%s updated.', $table));
  371. }
  372. }
  373. }
  374. }
  375. }
  376. /**
  377. * get the option parser
  378. *
  379. * @return void
  380. */
  381. public function getOptionParser() {
  382. $plugin = array(
  383. 'help' => __d('cake_console', 'The plugin to use.'),
  384. );
  385. $connection = array(
  386. 'help' => __d('cake_console', 'Set the db config to use.'),
  387. 'default' => 'default'
  388. );
  389. $path = array(
  390. 'help' => __d('cake_console', 'Path to read and write schema.php'),
  391. 'default' => APP . 'Config' . DS . 'Schema'
  392. );
  393. $file = array(
  394. 'help' => __d('cake_console', 'File name to read and write.'),
  395. 'default' => 'schema.php'
  396. );
  397. $name = array(
  398. 'help' => __d('cake_console', 'Classname to use. If its Plugin.class, both name and plugin options will be set.')
  399. );
  400. $snapshot = array(
  401. 'short' => 's',
  402. 'help' => __d('cake_console', 'Snapshot number to use/make.')
  403. );
  404. $dry = array(
  405. 'help' => __d('cake_console', 'Perform a dry run on create and update commands. Queries will be output instead of run.'),
  406. 'boolean' => true
  407. );
  408. $force = array(
  409. 'short' => 'f',
  410. 'help' => __d('cake_console', 'Force "generate" to create a new schema'),
  411. 'boolean' => true
  412. );
  413. $write = array(
  414. 'help' => __d('cake_console', 'Write the dumped SQL to a file.')
  415. );
  416. $parser = parent::getOptionParser();
  417. $parser->description(
  418. __d('cake_console', 'The Schema Shell generates a schema object from the database and updates the database from the schema.')
  419. )->addSubcommand('view', array(
  420. 'help' => __d('cake_console', 'Read and output the contents of a schema file'),
  421. 'parser' => array(
  422. 'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
  423. 'arguments' => compact('name')
  424. )
  425. ))->addSubcommand('generate', array(
  426. 'help' => __d('cake_console', 'Reads from --connection and writes to --path. Generate snapshots with -s'),
  427. 'parser' => array(
  428. 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'snapshot', 'force'),
  429. 'arguments' => array(
  430. 'snapshot' => array('help' => __d('cake_console', 'Generate a snapshot.'))
  431. )
  432. )
  433. ))->addSubcommand('dump', array(
  434. 'help' => __d('cake_console', 'Dump database SQL based on a schema file to stdout.'),
  435. 'parser' => array(
  436. 'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
  437. 'arguments' => compact('name')
  438. )
  439. ))->addSubcommand('create', array(
  440. 'help' => __d('cake_console', 'Drop and create tables based on the schema file.'),
  441. 'parser' => array(
  442. 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot'),
  443. 'args' => array(
  444. 'name' => array(
  445. 'help' => __d('cake_console', 'Name of schema to use.')
  446. ),
  447. 'table' => array(
  448. 'help' => __d('cake_console', 'Only create the specified table.')
  449. )
  450. )
  451. )
  452. ))->addSubcommand('update', array(
  453. 'help' => __d('cake_console', 'Alter the tables based on the schema file.'),
  454. 'parser' => array(
  455. 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot'),
  456. 'args' => array(
  457. 'name' => array(
  458. 'help' => __d('cake_console', 'Name of schema to use.')
  459. ),
  460. 'table' => array(
  461. 'help' => __d('cake_console', 'Only create the specified table.')
  462. )
  463. )
  464. )
  465. ));
  466. return $parser;
  467. }
  468. }