SchemaShell.php 15 KB

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