PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

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

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